注意用指针记录节点的前一个节点位置。
代码:
/**
* 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) {
if(head == null || head.next == null) return head;
ListNode nex = head.next.next;
ListNode newHead = head.next;
head.next.next = head;
head.next = nex;
ListNode prev = head;
ListNode cur = nex;
while(cur != null && cur.next != null){
nex = cur.next.next;
prev.next = cur.next;
cur.next.next = cur;
cur.next = nex;
prev = cur;
cur = nex;
}
return newHead;
}
}
Swap Nodes in Pairs; Data Structure; Linked List; Pointer;
原文:http://www.cnblogs.com/5683yue/p/5134890.html