链表高频算法题Python代码

目录

单链表排序

删除有序链表中的重复元素

删除有序链表中重复的元素II


单链表排序

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

进阶:你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?

class Solution:
    def sortInList(self , head ):
        # write code here
        def sort(head, tail):
            if not head: return head
            if head.next == tail:
                head.next = None
                return head
            fast, slow = head, head
            while fast != tail:
                fast = fast.next
                slow = slow.next
                if fast != tail:
                    fast = fast.next
            mid = slow
            return merge(sort(head, mid), sort(mid, tail))
        def merge(head1, head2):
            dummy = ListNode(0)
            tmp, tmp1, tmp2 = dummy, head1, head2
            while tmp1 and tmp2:
                if tmp1.val < tmp2.val:
                    tmp.next = tmp1
                    tmp1 = tmp1.next
                else:
                    tmp.next = tmp2
                    tmp2 = tmp2.next
                tmp = tmp.next
            if tmp1:
                tmp.next = tmp1
            if tmp2:
                tmp.next = tmp2
            return dummy.next
        return sort(head, None)

题解:递归排序

删除有序链表中的重复元素

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

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

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

删除有序链表中重复的元素II

给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。
 

class Solution:
    def deleteDuplicates(self , head ):
        # write code here
        if not head: return head
        dummy = ListNode(0)
        dummy.next = head
        cur = dummy
        while cur.next and cur.next.next:
            if cur.next.val == cur.next.next.val:
                x = cur.next.val
                while cur.next and cur.next.val == x:
                    cur.next = cur.next.next
            else:
                cur = cur.next
        return dummy.next

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值