https://leetcode.com/problems/swap-nodes-in-pairs/
这种题都可以用dummy node来解决,不过要注意其中node指针换来换去的细节问题,很容易错。
代码如下:
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next == null) return head;
ListNode dummy = new ListNode(0);
ListNode traverse = dummy;
while(head!=null && head.next!=null){
ListNode tmp = head.next.next;
traverse.next = head.next;
head.next.next = head;
traverse = head;
head = tmp;
}
traverse.next = head;
return dummy.next;
}
}