在 Java 中删除链表中的备用节点



我正在编写用于删除链表中备用节点的代码。 为什么它会无限循环? 输入 : 5->11->13->12->15->5 预期操作 : 5->13->15->5

public Node deleteAlternate(Node head)
{
Node p = head;
Node q = head.next;
while(q!=null && q.next !=null)
{
p.next = q.next;
q.next = p ;
p.next = q;
System.out.println(p.data+"   "+q.data);
}
return head;
}

块引用

由于有几点,一些提示:

  • 保持代码/逻辑简单。如果不需要,则没有具有两个变量和两个条件的循环。在这里,您是线性行走的。
  • 循环条件(q(必须改变,所以q必须行走。
  • 调试
  • ,甚至最好先在纸上调试。

所以像这样:

public Node deleteAlternate(Node head)
{
Node p = head;
while (p != null) {
if (p.next != null) {
p.next = ... // delete the next.
}
p = p.next;
}
return head; // head is never deleted.
}
public void DeleteAlternateNodes(Node head) {
Node current=head;
Node prev=head;
if(head==null)
return;
else if(current.next==null)
return;
while(current!=null && current.next!=null)
{
prev.next=current.next.next;
current=current.next;
prev=prev.next;
}
}

删除备用节点(头(;

I/P:5 10 15 25 3525 40 O/P:5 15 35 40

/**
*
* Input : 1 -> 2 -> 3 -> 4 -> 5
* Output : 1 -> 3 -> 5
*
* Input : 1
* Output : 1
*
* Input : 1 -> 2
* Output : 1
*
* Input : null
* Output : null
*
*/
public Node deleteAlternateNodes(Node<T> head) {
Node<T> newHead = head;
Node nextNode = null;
while(head != null && head.next != null) {
nextNode = head.next;
head.next = nextNode.next;
head = head.next;
}
return newHead;
}

最新更新