Reverse Doubly Linked List: Efficient Algorithm and Explanation
reverse() {
let currNode = this.head; //current node starts at the head of the list
let prevNode = null; //initialize previous node as null
let nextNode = null; //initialize next node as null
while (currNode) { //while there is a current node
nextNode = currNode.next; //store the next node
prevNode = currNode.previous; //store the previous node
currNode.next = prevNode; //change the next node of the current node to link to the previous node
currNode.previous = nextNode; //change the previous node of the current node to link to the next node
prevNode = currNode; //move the previous node one step forward
currNode = nextNode; //move the current node one step forward
}
this.tail = this.head; //reset the tail to the head
this.head = prevNode; //reset the head to the last node (which is now the first node after reversing)
return this;
}
This code implements a function to reverse a doubly linked list. It uses three pointers: currNode, prevNode, and nextNode. The algorithm works as follows:
-
Initialization:
currNodeis initialized to the head of the list.prevNodeis initialized tonull(since there is no node before the head).nextNodeis initialized tonull.
-
Iteration:
- The loop continues as long as there is a
currNode(we haven't reached the end of the list). - Inside the loop:
- The
nextNodeis stored to keep track of the node after the current one. - The
prevNodeis stored. - The
nextpointer of thecurrNodeis changed to point to theprevNode(reversing the direction). - The
previouspointer of thecurrNodeis changed to point to thenextNode(reversing the direction). - The
prevNodeis updated to the current node, moving theprevNodeone step forward. - The
currNodeis updated to thenextNode, moving thecurrNodeone step forward.
- The
- The loop continues as long as there is a
-
Resetting Head and Tail:
- After the loop, the
tailis set to thehead(which is now the last node of the reversed list). - The
headis set to theprevNode(which is now the first node of the reversed list).
- After the loop, the
-
Return:
- The function returns
this, referring to the current list object after the reversal operation.
- The function returns
原文地址: https://www.cveoy.top/t/topic/qhpf 著作权归作者所有。请勿转载和采集!