Skip to content

Latest commit

 

History

History
42 lines (36 loc) · 1.04 KB

24.md

File metadata and controls

42 lines (36 loc) · 1.04 KB

思路

  • 25 题 一致,k 固定为 2

代码

// Java
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode pre = dummyHead;
        ListNode end = dummyHead;
        while (end.next != null) {
            for (int i = 0; i < 2 && end != null; i++) {
                end = end.next;
            }
            if (end == null) {
                break;
            }
            ListNode start = pre.next;
            ListNode next = end.next;
            end.next = null;
            pre.next = swap(start);
            end.next = next;
            pre = end;
        }
        return dummyHead.next;
    }

    private ListNode swap(ListNode head) {
        int val = head.val;
        head.val = head.next.val;
        head.next.val = val;
        return head;
    }
}