【发布时间】:2013-03-01 04:33:17
【问题描述】:
大家好,我在尝试实现单链表的附加方法时遇到了麻烦。 这是代码:
public void append ( int item ) {
//inserts item to the end of the list
if ( head == null){
head = new LinkInt();
curr = head;
curr.elem = item;
}
else{
LinkInt temp = head;
while ( temp.next != null){
temp = temp.next;}
temp.elem = item;
}
}
这是我的打印方法(不确定是否正确):
public void print () {
//outprint the array
//ie. <1, 2, |3, 4>
if ( head == null) {
System.out.print("<");
System.out.print(">");
}
else{
LinkInt temp = head;
System.out.print("<");
while ( temp != null) {
if ( temp == curr){
System.out.print( "|" + temp.elem + ","); }
else{
System.out.print( temp.elem );
System.out.print(",");}
temp = temp.next;
}
System.out.print(">");
}
}
}
问题来了:
假设附加了 3 ->>> 我得到了 但是如果我在 ->>>> 之后添加了 5,我会得到 删除我的第一个项目。
请帮帮我:(
【问题讨论】:
-
为什么不存储对尾元素的引用。会让事情变得更快。