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.
给一个链表,两两交换。我的思路是两对两对看,但是分为三种情况,这对和后面的情形是:1-2-3-4;1-2-3;1-2;
然后根据不同的情况写出他们的交换策略~代码里有注释,看不懂的可以看注释明白我的思路~
附赠main函数供各位测试!!!
public class SwapNodesinPairs {
public static void main(String args[]){
SwapNodesinPairs dp = new SwapNodesinPairs();
ListNode head = new ListNode(1);
ListNode p1 = new ListNode(2);
head.next=p1;
ListNode p2 = new ListNode(3);
p1.next = p2;
ListNode p3 = new ListNode(4);
p2.next = p3;
ListNode p4 = new ListNode(5);
p3.next = p4;
prinf(head);
prinf(dp.swapPairs(head));
}
private static void prinf(ListNode input){
while(input!=null) {
System.out.print(input.val+"->");
input = input.next;
}
System.out.println();
}
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null) return head;
ListNode p=head;
ListNode start = head.next;
while(p!=null&&p.next!=null){
ListNode nxt = p.next;
//如果后面四个都有,2连向1,1连向4,4连向3,然后切记让下一轮的p得等于3(但是由于这个算法会跳过3,所以提前存好3)
if(p.next.next!=null&&p.next.next.next!=null){
p.next=nxt.next.next;
ListNode tmp = nxt.next;//提前存好3
nxt.next=p;
p=tmp;//让下一个p等于3,如果p.next的话下一个就是4了,而且3被永远跳过了
}
//如果后面有三个,就是这一对完了,还剩一个,那么最后那个不动,这两个交换
else if(p.next.next!=null&&p.next.next.next==null){
p.next=nxt.next;
nxt.next=p;
p=p.next;
}
//就剩最后两个,自己交换即可
else if(p.next.next==null){
nxt.next=p;
p.next=null;
}
}
return start;
}
}
【Leetcode】Swap Nodes in Pairs in JAVA 难得的一次写对不带改的。。附赠测试程序like always
原文:http://blog.csdn.net/qbt4juik/article/details/41422843