Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
解决link list类的问题可以分为两步。
第一步,找出第一阶段的指针该怎么变换。
第二步,找出怎么移动指针到下一阶段。
先来看第一步。
我是利用3个指针来控制,cur指向偶数位的节点(这里是2),pre指向cur的前面一个节点(1),prepre 指向 pre的前面一个节点(一开始让prepre指向伪造的头节点fakeNode)。
如何实现交换?让2指向1,1指向3-> 4就可以了,同时让prepre 指向 2, 将各部分串联起来。
pre.next = cur.next;
cur.next = pre;
prepre.next = cur;
接下来是第二部,指针该怎么移动。
翻转完1,2就轮到3,4了,我们想让cur指向4,pre指向3,prpre指向1
prepre = pre;
cur = pre.next.next;
pre = pre.next;
关键:手动模拟!
运行时间:
代码:
public class SwapNodesinPairs {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode fakeNode = new ListNode(-1);
fakeNode.next = head;
ListNode prepre = fakeNode, pre = head, cur = head.next;
while (cur != null) {
pre.next = cur.next;
cur.next = pre;
prepre.next = cur;
if (pre.next == null || pre.next.next == null) {
break;
} else {
prepre = pre;
cur = pre.next.next;
pre = pre.next;
}
}
return fakeNode.next;
}
}