第一道
题目:https://leetcode.cn/problems/partition-list/description/
86 Partition List
这个题解决的时候,无非就是把链表中小于X的元素摘出来形成一个链表,同时也把大于等于X的元素摘出来形成另外一个链表。最后把这两个链表合并。这个地方就牵扯到一个dummy节点的技巧
代码如下
class Solution:def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:dummy1 = ListNode(-1)dummy2 = ListNode(-1)p1 = dummy1p2 = dummy2while head:if head.val < x:p1.next = ListNode(head.val)p1 = p1.nextelse:p2.next = ListNode(head.val)p2 = p2.nexthead = head.nextp1.next = dummy2.nextreturn dummy1.next
第二道:
https://leetcode.cn/problems/merge-k-sorted-lists/description/
23. Merge k Sorted Lists
将多个链表合并成一个链表,按照升序排列,这个地方用到了一个常用的python库:heapq,无非就是取出元素之后加入到堆中,再依次弹出
import heapqclass Solution:def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:heap = []for l in lists:head = lwhile head:heapq.heappush(heap, (head.val))head = head.nextdummy = ListNode(-1)head = dummywhile heap:val = heapq.heappop(heap)head.next = ListNode(val)head = head.nexthead.next = Nonereturn dummy.next
第三道:
https://leetcode.cn/problems/add-two-numbers/
2. Add Two Numbers
这个题目对于python来说还是相对比较加单的,python的数据类型转换更为方便一些
class Solution:def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:head = l1sum1 = 0cnt0 = 0while head:sum1 += head.val * (10 ** cnt0)cnt0 += 1head = head.nexthead = l2sum2 = 0cnt1 = 0while head:sum2 += head.val * (10 ** cnt1)cnt1 += 1 head = head.nextsum = sum1 + sum2reversed = str(sum)[::-1]dummy = ListNode(-1)p = dummyfor i in reversed:p.next = ListNode(int(i))p = p.nextreturn dummy.next