给出一个单向链表,两两交换node,已经交换过的node不参与下一轮交换。
思路:
交换2个node需要3个指针,pre, cur, post, 分别指向前一节点,当前节点,下一节点。
而head节点是指向第一个元素的,第一个元素发生变动时,head也要变。为了不这么麻烦,新定义一个newHead指针,newHead.next指向链表的第一个元素。这样做的好处是,不管第一个元素变成谁,最后只需要返回newHead.next。
这里用head代替cur指针(可以少申请一个指针内存)。
刚开始时pre = newHead, cur = head, post = head.next, pre->head->post.
交换节点后变成pre->post->head.
下一轮这3个指针都需要移动,首先pre=head, 如果pre.next==null,就结束了。
再移动head=pre.next, post=head.next, 这样它们又恢复了pre->head->next的关系。继续下一轮。
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode newHead = new ListNode();
newHead.next = head;
ListNode pre = newHead;
ListNode post = head.next;
//head is cur node
while(post != null) {
//swap
head.next = post.next;
pre.next = post;
post.next = head;
//after swap is: pre->post->head
pre = head;
head = pre.next;
if(head == null) break;
post = head.next;
}
return newHead.next;
}