程序有点长,但很简单,就是一个普通的链表。
请问程序中的
end.next = newEnd;
end = newEnd;
这两条语句有什么用处?第二条没有看懂~~
public class LinkedList { public LinkedList() {
}
public LinkedList(Object[] items){
if (items != null){
for (int i = 0; i < items.length; i++){
addItem(items[i]);
}
current = start;
}
}
public void addItem(Object item){
ListItem newEnd = new ListItem(item);
if (start == null){
start = end = newEnd;
} else {
end.next = newEnd;
end = newEnd;
}
}
public Object getFirst(){
current = start;
return start == null ? null : start.item;
}
public Object getNext(){
if (current != null){
current = current.next;
}
return current == null ? null : current.item;
}
private ListItem start = null;
private ListItem end = null;
private ListItem current = null;
private class ListItem {
public ListItem(Object item){
this.item = item;
next = null;
}
public String toString(){
return "ListItem" + item;
}
ListItem next;
Object item;
}
}
请问程序中的
end.next = newEnd;
end = newEnd;
这两条语句有什么用处?第二条没有看懂~~
public class LinkedList { public LinkedList() {
}
public LinkedList(Object[] items){
if (items != null){
for (int i = 0; i < items.length; i++){
addItem(items[i]);
}
current = start;
}
}
public void addItem(Object item){
ListItem newEnd = new ListItem(item);
if (start == null){
start = end = newEnd;
} else {
end.next = newEnd;
end = newEnd;
}
}
public Object getFirst(){
current = start;
return start == null ? null : start.item;
}
public Object getNext(){
if (current != null){
current = current.next;
}
return current == null ? null : current.item;
}
private ListItem start = null;
private ListItem end = null;
private ListItem current = null;
private class ListItem {
public ListItem(Object item){
this.item = item;
next = null;
}
public String toString(){
return "ListItem" + item;
}
ListItem next;
Object item;
}
}
再将newEnd指定为结尾
再将newEnd指定为结尾
public ListItem(Object item){
this.item = item;
next = null;
}
在addItem方法中
ListItem newEnd = new ListItem(item);后
这个newEnd的next是null.
end = newEnd;后
end.next也就是null
"链表"顾名思义,表中的元素都是靠链接来关联的.
这里是加在结尾加入新元素,而现在链表中的结尾是end.
很自然的将end的next指向新加进来的元素(newEnd)的就可以了.
这就是end.next = newEnd
然后你要告诉链表,这个newEnd变成了结尾
这就是end = newEnd;说实话newEnd不如改叫newItem...
end.next = null;进行完第一条语句:
end.next = newEnd;进行完第二条语句:
end.next = null;这样一来还是没明白end.next = newEnd这句话作了什么?
每个格子分成两半,上面一半是存的item,下面一半是next
然后将第一个格子的next连到第二个格子的item上...其余的都这么做.
这个时候最后一个格子的next谁都没有指,是null.
然后画个箭头,指向最后一个格子,把箭头标上end.那么end的next也就是空的...ListItem newEnd = new ListItem(item);
这句表示:在最后面再画个同样的格子这个格子叫newEnd.
此时这个newEnd的next是nullend.next = newEnd;
这句表示:把end指的那个格子的next指向这个newEndend = newEnd;
这句表示:把end这个箭头指向newEnd这个格子这时候新的元素添加完了,样子和原来没什么区别,只不过多了一个元素,而end那个箭头还是指向这个链表的最后一个.end的next还是null