目录
单链表排序
给你链表的头结点 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