Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Assume that we have linked list 1 → 2 → 3 → Ø, we would like to change it to Ø ← 1 ← 2 ← 3.
- While you are traversing the list, change the current node's next pointer to point to its previous element. Since a node does not have reference to its previous node, you must store its previous element beforehand. You also need another pointer to store the next node before changing the reference. Do not forget to return the new head reference at the end!
- */
- /**
- * Definition for singly-linked list.
- * function ListNode(val) {
- * this.val = val;
- * this.next = null;
- * }
- */
- /**
- * @param {ListNode} head
- * @return {ListNode}
- */
- function ListNode(val) {
- this.val = val;
- this.next = null;
- }
- var reverseList = function(head) {
- var node = head;
- var previous = null;
- while(node) {
- // save next or you lose it!!!
- var save = node.next;
- // reverse pointer
- node.next = previous;
- // increment previous to current node
- previous = node;
- // increment node to next node or null at end of list
- node = save;
- }
- return previous;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement