Given 1->2->3->4, you should return the list as 2->1->4->3.
public static ListNode swapPairs(ListNode head) {
ListNode node = new ListNode(-1);
node.next = head;
ListNode cur = node;
while (cur.next!=null&&cur.next.next!=null) {
ListNode node1 = cur.next;
ListNode node2 = cur.next.next;
cur.next = node2;
node1.next = node2.next;
node2.next = node1;
cur = node1;
}
return node.next;
}
网友评论