leetcode链表专题
23. 合并K个升序链表
普通归并排序 + python迭代器
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
def merge(head1: Optional[ListNode], head2: Optional[ListNode]) -> Optional[ListNode]:
if not head1:
return head2
if not head2:
return head1
dummy = ListNode()
tail = dummy
while head1 and head2:
if head1.val <= head2.val:
tail.next = head1
head1 = head1.next
else:
tail.next = head2
head2 = head2.next
tail = tail.next
tail.next = head1 if head1 else head2
return dummy.next
it = iter(lists)
dummy = ListNode()
while it:
try:
dummy.next = merge(dummy.next, next(it))
except StopIteration:
break
return dummy.next
- K 个一组翻转链表
反转链表 + 指针
class Solution:
def reverse(self, head: ListNode, tail: ListNode):
prev = tail.next
p = head
while prev != tail:
nex = p.next
p.next = prev
prev = p
p = nex
return tail, head
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
dummy = ListNode(0, head)
pre = dummy
while head:
tail = pre
for i in range(k):
tail = tail.next
if not tail:
return dummy.next
nex = tail.next
head, tail = self.reverse(head, tail)
pre.next = head
tail.next = nex
pre = tail
head = tail.next
return dummy.next
- 旋转链表
约束条件多的一批
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head:
return
node, length = head, 0
while node:
length += 1
node = node.next
k = k%length if k >= length else k
fast, slow = head, head
while k:
fast = fast.next
k -= 1
while fast.next:
fast = fast.next
slow = slow.next
if slow == fast:
return head
node = slow.next
slow.next = None
fast.next = head
return node
- 删除排序链表中的重复元素 II
双指针
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(None, next=head)
node = dummy
while node.next:
cur = node.next
while cur.next and cur.val == cur.next.val:
cur = cur.next
if cur == node.next:
node = cur
else:
node.next = cur.next
return dummy.next