leetcode24.两两交换链表中的节点——学习笔记

这篇博客介绍了解决LeetCode上的《交换链表中的相邻节点》问题的解决方案。通过递归的思想,将链表节点两两交换,最终返回交换后的链表头节点。代码中定义了递归出口,然后交换前两个节点,并将处理好的链表返回至上一层,直至完成所有节点的交换。
摘要由CSDN通过智能技术生成

题目:力扣icon-default.png?t=LA46https://leetcode-cn.com/problems/swap-nodes-in-pairs/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }
        ListNode temp = head.next;
        head.next = swapPairs(temp.next);
        temp.next = head;
        return temp;
    }
}

 

思路:总结来说就是“递归”的思想,把问题一步步简化到最简单的形式,然后再将结果一层一层回溯,将已经处理好的部分链表返回到上一层,直至回到第一层则得出题目所求的链表。这份代码是学习了大佬的博客,然后再自己跟着编写的。

 1.定义递归出口。简而言之,就是当链表无法交换的时候便结束了呗~

if(head==null || head.next==null){
    return head;
}

2.一共三个节点head, temp, swapPairs(temp.next),我们需要做的就是交换前两个节点,因为第三个是已经处理完的链表部分,不需要动它。

ListNode temp = head.next;
head.next = swapPairs(temp.next);
temp.next = head;

3.把处理后的链表返回至上一层,直至递归出口为止。

return temp;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hokachi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值