Algorithm 如何迭代地反转linkedList,理解我在网上找到的代码

Algorithm 如何迭代地反转linkedList,理解我在网上找到的代码,algorithm,linked-list,swap,iteration,Algorithm,Linked List,Swap,Iteration,我试图编写不同的面试问题。一个非常经典的问题是反转单链接列表。 我在网上找到了这段代码,并对其进行了注释,但当我们交换指针时,我真的不知道发生了什么 public static LinkedList iterativeReverse(LinkedList linkedList) { if (linkedList == null || linkedList.next == null) { //We check if the list is

我试图编写不同的面试问题。一个非常经典的问题是反转单链接列表。 我在网上找到了这段代码,并对其进行了注释,但当我们交换指针时,我真的不知道发生了什么

public static LinkedList iterativeReverse(LinkedList linkedList) {

    if (linkedList == null || linkedList.next == null) {  //We check if the list is 
                                                           empty or has one node and
                                                           accordingly we return the list if it were the case
        return linkedList;
    }

    LinkedList prevNode, currNode, nextNode; //Three pointers 
    prevNode = null; // Are those pointers 
    nextNode = null; // temporary pointers for the swapping?
    currNode = linkedList; //is this the node pointing to head that is going to eventually point to null?

    while (currNode != null) {  // As long as we haven't reached the end of the list
        nextNode = currNode.next; //here it gets complicated for me, I don't understand what is happening
        currNode.next = prevNode;
        prevNode = currNode;
        currNode = nextNode;
    }

    return prevNode;
}
请有人帮我找到解决这个问题的正确途径好吗


谢谢。

假设您有这样一个链接列表a-->b-->c,
prevNode
指向
a
currNode
指向
b

所以
nextNode=currNode.next将相当于点
nextNode
c

为了反转链表,我们需要将链接a-->b的方向更改为b-->a,这就是在中发生的情况:

currNode.next=prevNode

现在,剩下的唯一任务是将
prevNode
更新到b,并将
curNode
更新到c,然后重复该过程

prevNode = currNode;
currNode = nextNode;

如果您有一个源代码级调试器,您可以创建一个列表并逐步完成代码。在第一个循环中,nextNode设置为linkedList.next,然后linkedList.next设置为null,prevNode设置为linkedList,currNode设置为linkedList.next。