Advertisement
1988coder

24. Swap Nodes in Pairs

Jan 7th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/swap-nodes-in-pairs/
  3.  
  4. //   Definition for singly-linked list.
  5. class ListNode {
  6.     int val;
  7.     ListNode next;
  8.  
  9.     ListNode(int x) {
  10.         val = x;
  11.     }
  12. }
  13.  
  14. /**
  15.  * Iterative Solution
  16.  *
  17.  * Time Complexity: O(N)
  18.  *
  19.  * Space Complexity: O(1)
  20.  */
  21. class Solution1 {
  22.     public ListNode swapPairs(ListNode head) {
  23.         if (head == null || head.next == null) {
  24.             return head;
  25.         }
  26.  
  27.         ListNode dummy = new ListNode(-1);
  28.         dummy.next = head;
  29.         ListNode cur = head;
  30.         ListNode pre = dummy;
  31.  
  32.         while (cur != null && cur.next != null) {
  33.             ListNode nextNode = cur.next;
  34.             pre.next = nextNode;
  35.             cur.next = nextNode.next;
  36.             nextNode.next = cur;
  37.             pre = cur;
  38.             cur = cur.next;
  39.         }
  40.  
  41.         return dummy.next;
  42.     }
  43. }
  44.  
  45. /**
  46.  * Recursive Solution
  47.  *
  48.  * Time Complexity: O(N)
  49.  *
  50.  * Space Complexity: O(N)
  51.  */
  52. class Solution2 {
  53.     public ListNode swapPairs(ListNode head) {
  54.         if (head == null || head.next == null) {
  55.             return head;
  56.         }
  57.  
  58.         ListNode nextNode = head.next;
  59.         head.next = swapPairs(nextNode.next);
  60.         nextNode.next = head;
  61.  
  62.         return nextNode;
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement