【问题标题】:How to reverse a linkedList iteratively, understanding the code I found online如何迭代地反转一个链表,了解我在网上找到的代码
【发布时间】:2014-06-24 09:28:04
【问题描述】:

我正在尝试编写不同的面试问题。一个非常经典的问题是反转单链表。 我在网上找到了这段代码并对其进行了评论,但是我们交换指针的地方,我真的不明白发生了什么。

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

请有人让我走上解决这个问题的正确轨道吗?

谢谢。

【问题讨论】:

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

标签: algorithm linked-list swap iteration


【解决方案1】:

假设您有一个像这样 a-->b-->c 的链表,其中prevNode 指向acurrNode 指向b

所以nextNode = currNode.next; 相当于将nextNode 指向c

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

currNode.next = prevNode;

现在,剩下的唯一工作就是将prevNode 更新为 b,将curNode 更新为 c,然后重复该过程。

prevNode = currNode;
currNode = nextNode;

【讨论】:

    猜你喜欢
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2021-06-27
    • 2012-08-27
    • 2020-08-24
    • 1970-01-01
    • 2011-06-13
    相关资源
    最近更新 更多