思路:添加头节点,依次反转相邻元素,保持反转后的最后一个指针pre,当前被反转的第一个元素的指针cur,当前被反转的第二个元素的指针next(如果存在的话)。反转的思路和92. Reverse Linked List II差不多,只不过pre要移动。
迭代做法:
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: