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

时间:2017-07-09 20:36:09

标签: java singly-linked-list

我正在编写用于删除链表中备用节点的代码。为什么它进入无限循环? 输入: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;
}
  

块引用

3 个答案:

答案 0 :(得分:0)

由于有几点,一些提示:

  • 保持代码/逻辑简单。如果不需要,没有带有两个变量和两个条件的循环。在这里,你正在线性行走。
  • 必须更改循环条件(在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.
}

答案 1 :(得分:0)

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;
    }
}

DeleteAlternateNodes(头);

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

答案 2 :(得分:0)

 /**
 *
 * 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;
}
相关问题