24. Swap Nodes in Pairs

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.

My Solutions:

  • 新建dummy,dummy.next = head; 新建 curr, curr = dummy

  • curr.next 和 curr.next.next != null 循环

    • first 是 curr.next (1)

    • second 是 curr.next.next (2)

    • first 连上 second.next (1 --> 3 --> 4 -->5 ...)

    • curr 连上 second ( head -->2 --> 3 --> 4 -->5 ... )

    • curr.next 连上 first ( head -->2 --> 1 --> 3 --> 4 -->5 ... )

    • curr 变成 curr.next.next (1)

      • 下一循环中,first 是3,second是4。。。。。。

public class Solution {
    public ListNode swapPairs(ListNode head) {

        if(head == null) return null;
        if(head.next == null) return head;

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode curr = dummy;

        while(curr.next != null && curr.next.next != null) {
            ListNode first = curr.next;
            ListNode second = curr.next.next;
            first.next = second.next;
            curr.next = second;
            curr.next.next = first;
            curr = curr.next.next;
        }
        return dummy.next;
    }
}

Last updated