[LeetCode] 24. Swap Nodes in Pairs

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.

思路:

这道题不难,但是特别恶心,很容易形成死循环。多用指针。最好的方法是一个指向第一个节点之前,第二个指向第二个节点之前。然后依次处理各个指针的next。一定要画图,很容易搞昏。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null)
            return head;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode pre = dummy;
        while (head != null && head.next != null) {
            // dummy->n1->n2->->...
            // => dummy->n2->n1->...
            pre.next = head.next;
            head.next = head.next.next;
            pre.next.next = head;
             
            pre = head;
            head = head.next;
        }
        
        return dummy.next;
    }
}

 

你可能感兴趣的:([LeetCode] 24. Swap Nodes in Pairs)