Guest User

Untitled

a guest
Jul 17th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.53 KB | None | 0 0
  1. const swapPairs = head => {
  2. if (!head) return null;
  3.  
  4. let newHead = head.next || head;
  5.  
  6. let current = head;
  7. let last = null;
  8.  
  9. while (current) {
  10. const temp = current;
  11.  
  12. current = swapPair(last, current);
  13. last = temp;
  14. }
  15.  
  16. return newHead;
  17. };
  18.  
  19. /**
  20. * @return {*} next
  21. */
  22. const swapPair = (last, node) => {
  23. const temp = node.next;
  24. const next = temp && temp.next;
  25.  
  26. if (temp) {
  27. if (last) last.next = temp;
  28. temp.next = node;
  29. node.next = null;
  30. } else {
  31. if (last) last.next = node;
  32. }
  33.  
  34. return next;
  35. };
Add Comment
Please, Sign In to add comment