向自定义单向链表增加数据, 出现死循环
向自定义单向链表增加数据, 出现死循环。debug了好久, 也没看出来原因。鄙视自己了好一会儿后, 决定发到CSDN求救。 多谢了!
单向链表 死循环
public class LinkedArray {
private Entry root;
private int count;
public static void main(String[] args) {
LinkedArray la = new LinkedArray();
for (int i = 0; i < 10; i++) {
la.add(i+"");
}
}
public LinkedArray() {
}
private class Entry{
private String data;
private Entry next;
private boolean add(String data){//有死循环
while(this.next!=null){
this.next.add(data);
}
if(this.next==null){
this.next = new Entry(data);
}
return true;
}
public Entry(String data) {
this.data = data;
}
}
public boolean add(String value){
if(value == null){
return false;
}
this.count++;
if(root==null){
root = new Entry(value);
}else{
this.root.add(value);
}
return true;
}
}
import java.util.Iterator;
/**
* 带表头的单向链表。
* 可以用迭代器,遍历里面的元素。
*/
public class OneWayList<T> implements Iterable<T>{
class Entry{
T data;
Entry next;
public Entry(T data) {
this.data = data;this.next=null;
}
}
/**
* 单向链表的表头,表头不存放数据。
*/
private Entry header = new Entry(null);
public void add(T data){
Entry tail = header;
while(tail.next!=null){
tail = tail.next;//指针后移
}
tail.next = new Entry(data);
}
/**
* 迭代器
*/
private class Iter implements Iterator<T>{
Entry p = header;
public boolean hasNext() {
return p.next!=null;
}
public T next() {
p = p.next;
return p.data;
}
public void remove() {
throw new IllegalStateException("Not support this operation.");
}
}
public Iterator<T> iterator() {
return new Iter();
}
/**
* 测试用例
*/
public static void main(String[] args) {
OneWayList<String> la = new OneWayList<String>();
for (int i = 0; i < 10; i++) {
la.add(i+"");
}
for(String s :la){
System.out.println(s);
}
}
}
public class LinkedArray {
private Entry root;
private int count;
private class Entry {
private String data;
private Entry next;
public Entry(String data) {
this.data = data;
}
}
public boolean add(String value) {
if (value == null) {
return false;
}
this.count++;
if (root == null) {//没有表头就要先判断根是否为空
root = new Entry(value);
} else {
Entry tail = root;
while(tail.next!=null){
tail = tail.next;
}
tail.next = new Entry(value);
}
return true;
}
public static void main(String[] args) {
LinkedArray la = new LinkedArray();
for (int i = 0; i < 10; i++) {
la.add(i + "");
}
}
}