Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. /*
  2. Assume that we have linked list 1 → 2 → 3 → Ø, we would like to change it to Ø ← 1 ← 2 ← 3.
  3.  
  4. 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!
  5. */
  6.  
  7. /**
  8. * Definition for singly-linked list.
  9. * function ListNode(val) {
  10. * this.val = val;
  11. * this.next = null;
  12. * }
  13. */
  14. /**
  15. * @param {ListNode} head
  16. * @return {ListNode}
  17. */
  18. function ListNode(val) {
  19. this.val = val;
  20. this.next = null;
  21. }
  22.  
  23. var reverseList = function(head) {
  24. var node = head;
  25. var previous = null;
  26.  
  27. while(node) {
  28. // save next or you lose it!!!
  29. var save = node.next;
  30. // reverse pointer
  31. node.next = previous;
  32. // increment previous to current node
  33. previous = node;
  34. // increment node to next node or null at end of list
  35. node = save;
  36. }
  37. return previous;
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement