Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
也就是
1->2->3->4->5
2->1->4->3->5
解法一:迭代
三个指针分别指向前中后,然后进行交换
save 1 0->2 1->3 2->1
public ListNode swapPairs2(ListNode h){
h=new ListNode(0,h);
ListNode point=h;
while(point!=null&&point.next!=null&&point.next.next!=null){
point=swapFrom(point);
point=point.next.next;
}
return h.next;
}
public ListNode swapFrom(ListNode h){
ListNode pre=h;
ListNode temp=h.next;
ListNode after=h.next.next;
pre.next=after;
temp.next=after.next;
after.next=temp;
return pre;
}
解法二:递归
(想了一会总算是推出来了)
推出来的过程
如果是一个,直接返回
如果是两个,直接交换
如果是三个,保存后面还没换的,然后换前两个,再把后面没换的换完接上
也就是
1->2->3->4->5
过程就是
1)保存2之后的链:3->4->5
2) 换1->2:其实就只要让h.next.next=h
3)把2之后的子串换好,接上前面换好的串(有点饿呐
public ListNode swapPairs(ListNode h) {
if(h==null||h.next==null)
return h;
ListNode next=h.next.next;
ListNode first=h.next;
h.next.next=h;
h.next=swapPairs(next);
return first;
}
这里需要注意,first存在的意义是我们让1后面的串变成 3开头的串换好之后的串,1后面就不是2了,就不能直接return 1.next,我们先要把2保存起来;