我正在尝试使用java实现链表数据结构,它可以很好地插入或删除第一个元素,但无法通过使用removeLast()方法删除最后一个元素。
我的链表节点类: LLNode类{ String value;LLNode next;
public LLNode(String value){
this.value = value;
this.next = null;
}
}我的包含head节点的链表类:
public class LL {
LLNode head;
public LL(){
this.head = null;
}
public void insertHead(LLNode input){
input.next = head;
this.head = input;
}
public void removeFirst(){
this.head = this.head.next;
}
public void removeLast(){
if (this.head == null || this.head.next == null){
this.head = null;
return;
}
LLNode current = this.head;
LLNode tmphead = current;
while(current.next.next != null){
current = current.next;
}
current.next.next = null;
this.head = tmphead ;
}
public void printAll(){
LLNode current = this.head;
while(current != null){
System.out.print(current.value+" ");
current = current.next;
}
System.out.println();
}
public static void main( String[] args){
LL test = new LL();
LL test2 = new LL();
String[] eben = {"one","two","three","four","five","six"};
for(int i =0;i<eben.length;i++){
test.insertHead(new LLNode(eben[i]));
}
test.printAll();
test.removeFirst();
test.printAll();
test.removeLast();
test.printAll();
}
}输出是这样的:
six five four three two one
five four three two one
five four three two one 尽管如此,它还是必须这样:
six five four three two one
five four three two one
five four three two我的实现出了什么问题?
发布于 2010-01-10 02:45:29
如果你需要很多代码和/或很多变量来完成这样的任务,你可能已经把自己弄得太复杂了。下面是我将如何使用removeLast()
public void removeLast() {
// avoid special case: List is empty
if (this.head != null) {
if (this.head.next == null) {
// handle special case: List has only 1 node
this.head = null;
} else {
LLNode prelast = this.head; // points at node before last (eventually)
while (prelast.next.next != null) prelast = prelast.next;
prelast.next = null;
}
}
}未经测试的!使用的风险自负。购买价格不退款。
发布于 2010-01-10 02:38:51
current.next.next = null;
应该是
current.next = null;
并且当尝试删除空列表的第一个元素时,实现会失败,并返回NPE
发布于 2010-01-10 02:45:17
while(current.next.next != null)不断进步,直到它成为真的。在这一点上设置current.next.next = null;。事实已经是这样了。
https://stackoverflow.com/questions/2034444
复制相似问题