【发布时间】:2016-08-06 01:42:11
【问题描述】:
我正在尝试删除具有给定键的节点,并且还想显示更新后的 Tail 和 Head 节点值。我可以删除第一个节点(头)并且无法删除尾节点请检查下面的代码
public void delete(int key){
Node current = head;
while(current.next.data != key){
current = current.next;
}
if(current.next.data == key ){ //deleting current node
current.next = current.next.next;
if(current.next == head)
tail = current;
else if(current == head)
head = current.next;
}
}
我的主要方法:
public class Caller {
public static void main(String args[]){
Linklist theList = new Linklist();
theList.insertFirst(22);
theList.insertFirst(44);
theList.insertFirst(55);
theList.insertFirst(66);
theList.delete(22);
System.out.println("deleting 22");
theList.display();
theList.delete(66);
System.out.println("Deleting 66");
theList.insertLast(99);
theList.insertLast(11);
theList.display();
}
}
我的 insertLast 方法:
public void insertLast(int data){
Node newNode = new Node(data);
Node current = head;
while(current.next != head){
current = current.next;
}
current.next = newNode;
newNode.next = head;
tail = newNode;
}
我的输出是:
deleting 22
Displaying list first ----> last
{ 66 }
{ 55 }
{ 44 }
Head : 66 Tail: 44
Deleting 66
这段代码之后什么都没有发生
【问题讨论】:
-
您能分享一下您的
insertLast()方法吗?这就是您的代码似乎卡住的地方——不在delete()内。 -
更新了@MickMnemonic
-
注意:“什么都没有发生”是非常模糊的......程序只是安静地退出,还是只是旋转直到您决定终止它?这是一个重要的区别。
-
@Lars 它不在那里旋转.. 只是正常退出,无论如何我找到了解决方案。谢谢
标签: java singly-linked-list circular-list