题目描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
注意:1 2 3 4 5 6 1和2换,然后就是3和4换,然后就是5和6 而不是冒泡式的换
递归算法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null)
{
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}
比如1 2 3 4 5 6
每次递归都会涉及两个元素,同时保存下一组【一组两个元素】的头元素,也就是保存一组内两个元素交换后的头元素,比如5 6
交换了,next保存的就是6这个元素,然后再把4 3
3的next设置为6
递归就是至底向上
下面看代码执行流程
1
[head=1] next = 2 next.next=3
[head=3] next = 4 next.next=5
[head=5] next=6 next.next=NULL 这时的head.next=null【5.next=NULL】
(当next.next传进去时返回null) next.next = head [6.next=5]
return next (return 6) 回到上一层递归
[head=3] head.next=6[3.next=6] next.next=head [4.next=3]
return next(return 4)
[head=1] 1.next=4 2.next=1 return 2
结束【2->1->4->3->6->5】