【发布时间】: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