LeetCode 24. Swap Nodes in Pairs
原题链接在这里:https://leetcode.com/problems/swap-nodes-in-pairs/
题目:
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4] Output: [2,1,4,3]
Example 2:
Input: head = [] Output: []
Example 3:
Input: head = [1] Output: [1]
Constraints:
- The number of nodes in the list is in the range
[0, 100]
. 0 <= Node.val <= 100
题解:
Create a dummy head and mark pointing to dummy. Every time reverse the next two nodes after mark.
And update mark to the new tail.
Time Complexity: O(n). n是list的长度.
Space: O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public ListNode swapPairs(ListNode head) { 13 if(head == null || head.next == null){ 14 return head; 15 } 16 17 ListNode dummy = new ListNode(-1); 18 dummy.next = head; 19 ListNode mark = dummy; 20 while(mark.next != null && mark.next.next != null){ 21 ListNode tail = mark.next; 22 ListNode cur = mark.next; 23 ListNode pre = cur; 24 ListNode temp; 25 26 cur = tail.next; 27 temp = cur.next; 28 cur.next = pre; 29 tail.next = temp; 30 mark.next = cur; 31 mark = tail; 32 } 33 34 return dummy.next; 35 } 36 }
AC C++:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* swapPairs(ListNode* head) { 14 if(!head || !head->next){ 15 return head; 16 } 17 18 ListNode* dummy = new ListNode(-1, head); 19 ListNode* mark = dummy; 20 while(mark->next && mark->next->next){ 21 ListNode* tail = mark->next; 22 ListNode* cur = tail; 23 ListNode* pre = cur; 24 ListNode* temp; 25 26 cur = tail->next; 27 temp = cur->next; 28 cur->next = pre; 29 tail->next = temp; 30 mark->next = cur; 31 mark = tail; 32 } 33 34 return dummy->next; 35 } 36 };
Recursion解法.
Time Complexity: O(n). Space: O(n), stack space.
AC Java:
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 public class Solution { 10 public ListNode swapPairs(ListNode head) { 11 if(head == null || head.next == null){ 12 return head; 13 } 14 ListNode n = head.next; 15 head.next = swapPairs(n.next); 16 n.next = head; 17 return n; 18 } 19 }