[LeetCode 024] Swap Nodes in Pairs

Swap Nodes in Pairs

Implementation

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode current = dummy;
        while (current.next != null && current.next.next != null) {
            ListNode p1 = current.next;
            ListNode p2 = current.next.next;
            p1.next = p2.next;
            p2.next = p1;
            current.next = p2;
            current = p1;
        }
        return dummy.next;
    }
}
原文地址:https://www.cnblogs.com/Victor-Han/p/5197011.html