Skip to main content

24 Swap Nodes in Pairs

Leetcode

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Example 1:

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1] Output: [1]

头差法。指针从头节点开始,如果右边有 2 个节点,交换顺序,向右移动 2 步,不断重复。

public ListNode swapPairs(ListNode head) {
ListNode h=new ListNode();
h.next=head;
ListNode t=h, tmp;
while(t.next!=null && t.next.next!=null){
tmp=t.next;
t.next=tmp.next;
tmp.next=tmp.next.next;
t.next.next=tmp;
t=tmp;
}
return h.next;
}