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%的用户

posted @ 2021-09-22 22:56  HEREISDAVID  阅读(78)  评论(0编辑  收藏  举报