Java双循环链表删除



我创建了一个双循环链表,并希望删除具有给定值的节点。如果我们假设存在一个节点值为11、12、13、14的循环双链表,其中11是头节点。然后,要删除值为11的节点,我们需要将前一个指针12设置为指向14,节点14的下一个指针必须设置为12,然后将12设置为头节点。所以,现在如果我们选择显示列表答案应该是12,13,14,但出乎意料的答案是12,13,14,11。当我在代码中添加第19行(下面提到的删除函数(时,就会显示预期的输出。因此,我想知道逻辑是否正确,我们是否更改了所有上一个和下一个指针值,以及为什么输出不同。如果我想删除第一个节点,即头节点,那么我们为什么要将下一个值设置为null(如第19行所示(下面提到的删除函数(

节点结构:

public class Node{
int data;
Node next,prev;   //next and previous pointers for a node
}

删除函数

1     public void del(int x)
2    {
3       Node n=head;
4      do{
5          if(n.data==x){break;}
6           n=n.next;
7       }
8     while(n.data!=x);
9       if(n.data==x && n!=head)  //for deleting any other node except first node
10       {
11         n.next.prev=n.prev;
12         n.prev.next=n.next;
13       }
14       else if(n.data==x && n==head)  //for first node deletion
15       {
16           head.next.prev=head.prev;
17           head.prev.next=head.next;
18           head=head.next;
19        // n.next=null;
20       }
21       else{System.out.println("Element not found");}
22    }

p.S:我还尝试将节点与下一个值一起打印,即使在将节点14的下一个指针从11更改为12(即删除11(之后,node.next仍然将11打印为节点14的一个。为什么下面给出的显示功能代码:

public void display()
{
Node n=head;

if (head != null)
{  
do
{
System.out.println(n.data+" and its next is "+n.next.data);
n=n.next;
}while(n!=head);
System.out.println("");
}
else{System.out.println("Please add an entry to the linked list");}
}

我试着让它尽可能简单,希望它能有所帮助。(很难阅读你的代码,所以我只是从头开始做的(

public class DoublyLinkedList {
// no null state
DoublyLinkedList prev = this, next = this;
int value;
public DoublyLinkedList(int value) {
this.value = value;
}
// add node to the back of the list
public void add(int value) {
DoublyLinkedList node = new DoublyLinkedList(value);
node.next = this;
node.prev = this.prev;
this.prev.next = node;
this.prev = node;
}
// remove the node
public void remove() {
prev.next = next;
next.prev = prev;
}
// find the node with given value
public DoublyLinkedList find(int value) {
DoublyLinkedList 
end = this.prev,
current = this;
while(current != null) {
if(current.value == value) return current;
if(current == end) break; // to prevent infinite cycle
current = current.next;
}
return null;
}
// dump the list
public void dump() {
DoublyLinkedList 
end = this.prev,
current = this;
while(current != null) {
System.out.print(current.value + " ");
if (current == end) break;
current = current.next;
}
System.out.println();
}
// testing
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList(1);
list.add(2);
list.add(3);
list.add(4);
list.dump();
list.find(3).remove();
list.dump();
}
}

最新更新