Swap Nodes in Pairs

Question:

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

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

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

Lesson Learned

  • ListNode的循环条件:一定要先判断cur2 != null,再判断cur2.next != null,也就是先确保最近的不等于null,再判断下一个,不然会出现NullPointerException。

  • 由于head和middle操作的不同,导致它们对循环条件的需求不同,这时比如这题如果只有两个数字则只判断head则不能进入这个循环,因此要给cur2.next加条件

  • head, cur2, cur1等是对reference地址的操作;cur1.next则是对链表的操作

Code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @return a ListNode
     */
    public ListNode swapPairs(ListNode head) {
        // Write your code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode cur1 = head;
        ListNode cur2 = head.next;
        // 这里一定要先判断cur2 != null,再判断cur2.next != null,
        // 也就是先确保最近的不等于null,再判断下一个
        // 不然会出现NullPointerException

        // 如果只有两个数字则不能进入这个循环,因此要给cur2.next加条件
        while (cur2 != null && (cur2.next != null || cur1 == head)) {
            if (cur1 == head) {
                // head, cur2, cur1等是对reference地址的操作;
                // cur1.next则是对链表的操作
                cur1.next = cur2.next;
                cur2.next = cur1;
                head = cur2;
                cur2 = cur1.next;
                continue;
            }
            cur1.next = cur2.next;
            cur2.next = cur2.next.next;
            cur1.next.next = cur2;
            cur1 = cur2;
            if (cur2 != null) {
                cur2 = cur2.next;
            }
        }
        return head;
    }
}