美文网首页
2019-06-10 剑指 反转链表

2019-06-10 剑指 反转链表

作者: mztkenan | 来源:发表于2019-06-10 21:09 被阅读0次

加入哑结点
1对空指针没有特殊处理
10min,和原来写的一模一样

class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if pHead==None:return pHead
        dead = ListNode(None)
        dead.next = pHead
        cur = pHead
        pre = dead
        while(cur!=None):
            next=cur.next
            cur.next=pre
            pre=cur
            cur=next
        pHead.next=None
        return pre

不加入哑结点,代码更简洁,但是不好理解

class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        pre=None
        cur=None
        while pHead!=None:
            cur=pHead
            pHead=pHead.next
            cur.next=pre
            pre=cur
        return cur

递归的解法,一次通过。8min

class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if pHead==None:return None #特殊情况
        if pHead.next==None:return pHead #边界情况
        next=pHead.next
        res=self.ReverseList(pHead.next)
        next.next=pHead
        pHead.next=None
        return res

相关文章

  • 2019-06-10 剑指 反转链表

    加入哑结点1对空指针没有特殊处理10min,和原来写的一模一样 不加入哑结点,代码更简洁,但是不好理解 递归的解法...

  • 反转链表

    《剑指offer》面试题24:输入一个链表,反转链表后,输出新链表的表头。 思路:反转链表就是将链表中每一个节点的...

  • 2022-03-26 链表反转回文

    反转链表:java版本: 剑指 Offer II 027. 回文链表[https://leetcode.cn/pr...

  • 24.反转链表

    剑指 Offer II 024. 反转链表[https://leetcode.cn/problems/UHnkqh...

  • 剑指offer:反转链表

    题目分析 输入一个链表,反转链表后,输出链表的所有元素。 代码

  • [剑指offer] 反转链表

    题目描述 输入一个链表,反转链表后,输出新链表的表头。 解题思路 设置三个指针,head为当前节点,pre为当前节...

  • 《剑指Offer》 反转链表

    题目描述 输入一个链表,反转链表后,输出新链表的表头。 源代码

  • 剑指offer:反转链表

    (Leetcode 206: reverse linked list)反转链表是比较重要的题,面试笔试经常会考。做...

  • [剑指Offer]反转链表

    本文首发于我的个人博客Suixin’s Blog原文: https://suixinblog.cn/2019/02...

  • 【剑指 offer】反转链表

    1、题目描述 定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。 样例输入:1->2->3-...

网友评论

      本文标题:2019-06-10 剑指 反转链表

      本文链接:https://www.haomeiwen.com/subject/uzwtfctx.html