Advertisement
Guest User

swap nodes in pairs

a guest
Oct 15th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode swapPairs(ListNode head) {
  11. if (head == null){
  12. return null;
  13. }
  14. if (head.next == null){
  15. return head;
  16. }
  17. ListNode returnNode = head.next;
  18. ListNode nextNext = returnNode.next;
  19. returnNode.next = head;
  20. recSwap(nextNext, head);
  21. return returnNode;
  22. }
  23.  
  24. public void recSwap(ListNode curr, ListNode temp){
  25. if (curr == null){
  26. temp.next = curr;
  27. } else if (curr.next == null){
  28. temp.next = curr;
  29. } else {
  30. ListNode next = curr.next;
  31. ListNode newCurr = next.next;
  32. next.next = curr;
  33. temp.next = next;
  34. recSwap(newCurr, curr);
  35. }
  36. }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement