Swap Nodes in Pairs 解答

Question

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Solution

这题的核心在于dummy node和list操作。

dummy -> 1 -> 2 -> 3 -> 4

prev   cur   next  tmp

我们用四个指针来完成操作。

1. 预存tmp: tmp = next.next

2. 更改next: next.next = cur

3. 更改cur: cur.next = tmp

4. 更改prev: prev.next = next

5. 更新prev, cur, next:

cur = tmp

if (cur != null): next = cur.next

prev = prev.next.next

最后返回dummy.next

我们看到循环结束的条件应该是tmp为null或者tmp.next为null.

 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 dummy = new ListNode(-1);
15         dummy.next = head;
16         ListNode prev = dummy, current = head, next = head.next, tmp;
17         while (next != null) {
18             tmp = next.next;
19             next.next = current;
20             current.next = tmp;
21             prev.next = next;
22             current = tmp;
23             prev = prev.next.next;
24             if (current == null) {
25                 break;
26             } else {
27                 next = current.next;
28             }
29         }
30         return dummy.next;
31     }
32 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4938928.html