LeetCode 24. Swap Nodes in Pairs 两两交换链表中的节点(Java)

题目:

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.

解答:

采用多个指针进行迭代。

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode prehead = new ListNode(0);
        prehead.next = head;
        ListNode pre = prehead;
        while(pre.next!=null && pre.next.next!=null) {
            ListNode node1 = pre.next;
            ListNode node2 = node1.next;
            ListNode temp = node2.next;
             
            pre.next = node2;
            node2.next = node1;
            node1.next = temp;
            pre = node1;
        }
        return prehead.next;
    }
}

你可能感兴趣的:(LeetCode)