**给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs**
完整的思考过程(递归方法结合分治策略):
- 最开始在纸上画图,按照题目修改指针的指向,发现问题可以拆成最小单位1->2,3->4,两个子问题(特殊的是链表长度为奇数,和最后空指针),然后合并子问题的解即可。
- 考虑用递归来解决,第一步肯定是考虑递归终止回归的条件,if(head == null || head.next == null) return head;
- 然后根据分治思想写下第三行代码head.next = swapPairs(head.next.next)。自己调用自己这一步的意义看成分解问题,因为从这里进入递归。head.next = 这部分看成连接链表(1->4),也就是合并子问题的解。
- 依旧是画图看过程,1要指向4那么应该把4返回,而最后答案是要返回2,这就到了解决子问题的时候,要使2指向1且返回2,就必须要存下指向2的指针,在第二行插入ListNode temp = head.next;
- 第四行2->1,然后第五行返回。
递归远远不止这点东西,做多了再回来做一个大总结。
/**
* 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 temp = head.next;
head.next = swapPairs(head.next.next);
temp.next = head;
return temp;
}
}
重写一遍
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode result = head.next;
head.next = result.next;
result.next = head;
head.next = swapPairs(head.next);
return result;
}
}