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

delete alternate nodes in linked list in 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;
}

Blockquote

由于有几点,一些小技巧:

  • 保持 code/logic 简单。如果不需要,则没有带有两个变量和两个条件的循环。在这里你正在直线行走。
  • 必须更改循环条件(在 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 35 25 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;
}