题目

24. 两两交换链表中的节点

题解


代码

/** * Definition for singly-linked list. public class ListNode { int val; ListNode * next; ListNode(int x) { val = x; } } */
public class code24 {

    public static ListNode swapPairs(ListNode head) {
        ListNode h = new ListNode(-1);
        h.next = head;
        ListNode pre = h;
        while (pre.next != null && pre.next.next != null) {
            ListNode node1 = pre.next;
            ListNode node2 = node1.next;
            ListNode later = node2.next;

            pre.next = node2;
            node2.next = node1;
            node1.next = later;

            pre = node1;
        }
        return h.next;
    }

    public static ListNode createList() {
        ListNode head = new ListNode(1);
        ListNode cur = head;
        for (int i = 2; i <= 10; i++) {
            cur.next = new ListNode(i);
            cur = cur.next;
        }
        return head;
    }

    public static void print(ListNode node) {
        if (node == null) {
            return;
        }
        ListNode current = node;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
        System.out.println("NULL");
    }

    public static void main(String[] args) {
        ListNode head = createList();
        print(head);
        ListNode res = swapPairs(head);
        print(res);
    }
}

参考

  1. Leetcode 24:两两交换链表中的节点(最详细解决方案!!!)
  2. Leetcode/src/0024-Swap-Nodes-in-Pairs/0024.py
  3. LeetCode : 24. 两两交换链表中的节点(Swap Nodes In Pairs)解答
  4. LeetCodeAnimation/notes/LeetCode第24号问题:两两交换链表中的节点.md
  5. Java非递归,0ms,O(n)
  6. 画解算法:24. 两两交换链表中的节点