zoukankan      html  css  js  c++  java
  • Leetcode python 206. 反转链表 83. 删除排序链表中的重复元素

    206. 反转链表

    给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

    示例 1:
    输入:head = [1,2,3,4,5]
    输出:[5,4,3,2,1]

    迭代

    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            pre, cur = None, head
            while cur:
                nxt = cur.next
                cur.next = pre
                pre = cur
                cur = nxt
            return pre
    

    执行用时:32 ms, 在所有 Python3 提交中击败了85.22%的用户
    内存消耗:15.5 MB, 在所有 Python3 提交中击败了56.20%的用户

    递归

    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            if not head or not head.next:
                return head
            newHead = self.reverseList(head.next)
            head.next.next = head
            head.next = None
            return newHead
    

    执行用时:36 ms, 在所有 Python3 提交中击败了65.86%的用户
    内存消耗:19.7 MB, 在所有 Python3 提交中击败了6.36%的用户

    83. 删除排序链表中的重复元素

    存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次

    返回同样按升序排列的结果链表。

    示例 1:
    输入:head = [1,1,2]
    输出:[1,2]

    示例 2:
    输入:head = [1,1,2,3,3]
    输出:[1,2,3]

    class Solution:
        def deleteDuplicates(self, head: ListNode) -> ListNode:
            if not head:
                return head
    
            cur = head
            while cur.next:
                if cur.val == cur.next.val:
                    cur.next = cur.next.next
                else:
                    cur = cur.next
    
            return head
    

    执行用时:40 ms, 在所有 Python3 提交中击败了60.98%的用户
    内存消耗:15 MB, 在所有 Python3 提交中击败了67.10%的用户

  • 相关阅读:
    01分数规划基本类型
    hdu3976
    hdu1430 康托展开+bfs预处理
    模板
    模板
    redis初始
    mybatis12
    mybatis13
    mybatis10
    springmvc10
  • 原文地址:https://www.cnblogs.com/hereisdavid/p/15322195.html
Copyright © 2011-2022 走看看