Leetcode 24. Swap Nodes in Pairs

思路:添加頭節點,依次反轉相鄰元素,保持反轉後的最後一個指針pre,當前被反轉的第一個元素的指針cur,當前被反轉的第二個元素的指針next(若是存在的話)。反轉的思路和92. Reverse Linked List II差很少,只不過pre要移動。node

迭代作法:spa

 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) return head;
12         ListNode dummy = new ListNode(0);
13         dummy.next = head;
14         ListNode pre = dummy, cur = head;
15         while(cur != null && cur.next != null) {//保證有2個能夠被反轉的元素
16             ListNode next = cur.next;
17             cur.next = next.next;
18             next.next = cur;
19             pre.next = next;
20             pre = cur;
21             cur = cur.next;
22         }
23         return dummy.next;
24     }
25 }

 

遞歸作法:指針

 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 || head.next == null) return head;//保證有2個能夠被反轉的元素
12         ListNode cur = head, next = cur.next;
13         cur.next = swapPairs(next.next);
14         next.next = cur;
15         return next;
16     }
17 }

 

Next challenges: Reverse Nodes in k-Groupcode

相關文章
相關標籤/搜索