简体   繁体   English

反向单向链表

[英]Reverse singly linked list

I have the below program to reverse elements in a singly linked list.我有以下程序来反转单链表中的元素。 I can't get it to work.我无法让它工作。 I have used simple swapping of variables technique to swap the nodes but when I print, it doesn't go beyond the first node.我使用了简单的变量交换技术来交换节点,但是当我打印时,它不会超出第一个节点。

public static void reverseLinkedList(Node head) {
    Node current = head;
    Node temp = null;
    while (current != null && current.next != null) {
        temp = current;
        current = current.next;
        current.next = temp;
    }
}
public static void printData(Node head) {
    Node currentNode = head;
    while (true) {
        System.out.println(currentNode.data);
        if (currentNode.next != null) {
            currentNode = currentNode.next;
        } else {
            break;
        }
    }
}

I prefer to return the head node after the function.我更喜欢在函数之后返回头节点。 Keeps thing simple保持简单

Node reverse(Node node) 
{ 
    Node prev = null; 
    Node current = node; 
    Node next = null; 
    while (current != null) { 
        next = current.next; 
        current.next = prev; 
        prev = current; 
        current = next; 
    } 
    node = prev; 
    return node; 
} 

Alternatively you can opt for the simpler recursive version或者,您可以选择更简单的递归版本

Node reverse(Node head) { 
    if(head == null) { 
        return head; 
    } 

    if(head.next == null) { 
        return head; 
    } 

    Node newHeadNode = reverse(head.next); 

    head.next.next = head; 
    head.next = null; 
    return newHeadNode; 
} 

You are assigning the next of the current variable to itself which is wrong.您正在将当前变量的下一个分配给自身,这是错误的。 You can do like below.你可以像下面这样做。

public void reverseLL(Node head) {
Node currentNode = head, prevLink = null, nextNode = null;

while (currentNode != null) {
    nextNode = currentNode.next;
    currentNode.next = prevLink;
    prevLink = currentNode;
    currentNode = nextNode;
}
head = prevLink;
}

In your algorithm the first two nodes of the list creates a loop after the first iteration of the while loop.It's better to use the below algorithm.在你的算法中,列表的前两个节点在 while 循环的第一次迭代后创建一个循环。最好使用下面的算法。

public static void reverseLinkedList(Node head) {
    Node current = head;
    Node prev = head;
    Node next = head.next;
    while (current != null && current.next != null) {
        current=next;
        next=current.next;
        current.next=prev;
        prev=current;
    }
   head=current;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM