【链表】【python】力扣24. 两两交换链表中的节点【超详细的注释和解释】

目录

说在前面的话

前言

一、题目(力扣24. 两两交换链表中的节点)

二、题目分析

实现完整代码(Python实现)

总结


说在前面的话

博主也好长一段时间没有更新力扣的刷题系列了,今天给大家带来一道经典题目,今天博主一改往常的风格,用python给大家实现,希望大家可以从中学到一些东西

前言

那么这里博主先安利一下一些干货满满的专栏啦!

手撕数据结构https://blog.csdn.net/yu_cblog/category_11490888.html?spm=1001.2014.3001.5482这里包含了博主很多的数据结构学习上的总结,每一篇都是超级用心编写的,有兴趣的伙伴们都支持一下吧!
算法专栏https://blog.csdn.net/yu_cblog/category_11464817.html

一、题目(力扣24. 两两交换链表中的节点)

二、题目分析

其实这道题标的是中等难度,其实并没有很难。
反转链表相信我们以前都实现过,我们可以直接调用接口。
现在要解决的问题就是怎么传参去反转

这里是实现的一些核心:

  1. 每走两步之后要断开链表,这就需要一个前导指针prev来记录遍历指针的前一个位置,方便断开链表(python没有指针的概念,这里博主只是这样说来方便大家理解)
  2. 调用接口之后我们需要拼接链表,因此我们也需要一个指针记录链表头的位置,我们用slow,遍历指针用fast,因为需要拼接,我们也需要slow的一个前导指针,方便拼接链表

实现完整代码(Python实现)

关于实现过程中的一些细节,博主给大家在代码中指出了!

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head==None: return head #处理特殊情况
        tail=ListNode()
        tail.next=None
        cur=head # 遍历链表
        
        while cur:
            next=cur.next
            cur.next=tail
            tail=cur # 把tail往后挪动
            cur=next
        # 找到结尾前最后一个节点 删除它
        cur=tail
        prev=None
        while cur.next:
            prev=cur
            cur=cur.next
        # 此时prev就是前一个
        prev.next=None

        return tail
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        newhead=ListNode()
        newhead.next=head
        fast=head
        fast_prev=newhead
        slow=head
        slow_prev=newhead

        while fast:
            for i in range(0,2):
                if not fast:
                    break
                fast_prev=fast
                fast=fast.next
            fast_prev.next=None
            slow_prev.next=self.reverseList(slow)
            # 这里的fast_prev已经更新了,需要找尾
            while fast_prev.next:
                fast_prev=fast_prev.next
            fast_prev.next=fast
            # 迭代
            slow_prev=fast_prev
            slow=fast
        return newhead.next

总结

看到这里 相信大家对这道题的解题方法已经有了一定的理解了吧?如果你感觉这篇文章对你有帮助的话,希望你可以持续关注,订阅专栏,点赞收藏都是我创作的最大动力!

( 转载时请注明作者和出处。未经许可,请勿用于商业用途 )
更多文章请访问我的主页

@背包https://blog.csdn.net/Yu_Cblog?type=blog

猜你喜欢

转载自blog.csdn.net/Yu_Cblog/article/details/126581405