今天一下午被这道题困惑好久,也是够笨呀。
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
.
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) return head;
// ListNode fakehead=null;
ListNode fakehead=new ListNode(-1);//注意这里要初始化赋值,-1这个数是任意的哈
fakehead.next=head;
ListNode ptr1=fakehead;
ListNode ptr2=head;
ListNode nextstart;
while(ptr2!=null && ptr2.next!=null){
nextstart=ptr2.next.next;
ptr2.next.next=ptr2;//对应图的第二步
ptr1.next=ptr2.next;//对应图的第三步
ptr2.next=nextstart;//对应图的第四步
ptr1=ptr2;//上面交换完成了,这里指针开始挪动到下一位置了
ptr2=ptr2.next;//指针挪动
}
return fakehead.next;
}
}
画了下图……
交换过程:
注意ptr1 ptr2就是两个指针,指针本次任务完成了,就接着移动,该指向下一轮啦。整个链表的头结点的使命,交给fakehead。也就是fakehead.next也就是常说的dummy。用这个假节点,next指向头结点,以便于保持和后续的节点处理一致。方便操作。
参考资料: