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.

这道题自己想的方法没有写出来,然后看了别人的解法。发现意思跟我的思路差不多,但细节很多地方我确实想不出来。linkedlist的题目很多细节问题,哪个该连哪个,对我来说现在很容易错或者陷入混乱。
该解法实际上仍然是维护三个pointers:prev, curt, temp.

以节点为偶数个时举例:


WechatIMG50.jpeg
WechatIMG51.jpeg

当节点数为偶数的时候,是curt == null退出循环;当节点数为奇数的时候,是curt.next == null退出循环。


WechatIMG52.jpeg
/**
 * 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 || head.next == null){
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        ListNode curt = head;
        while (curt != null && curt.next != null){
            ListNode temp = curt.next.next;
            curt.next.next = curt;
            prev.next = curt.next;
            curt.next = temp;
            prev = curt;
            curt = curt.next;
        }
        return dummy.next;
    }
}

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