made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 ''' ''' 解题思路: 1. 归并排序的链表实现 ''' EXAMPLES = [ ( (build_list_node(1, 2, 4), build_list_node(1, 3, 4)), build_list_node(1, 1, 2, 3, 4, 4), ), ] class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: n = ListNode(0) temp = n node1 = l1 node2 = l2 while not (node1 is None and node2 is None): node1_val = node1.val if node1 else math.inf node2_val = node2.val if node2 else math.inf
You may not modify the values in the list's node, only ondes itself may be changed. Example: Given 1->2->3->4, you should return the list as 2->1->4->3. ''' ''' 解题思路: 1. 交换偶数位置的节点,中间的位置存在上下关系。 2. ''' EXAMPLES = [ ( build_list_node(1, 2, 3, 4), build_list_node(2, 1, 4, 3), ), ] class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head: return [] node = head.next if node is None: r = head else: head.next = node.next
[ 1->4->5, 1->3->4, 2->6, ] Output: 1->1->2->3->4->5->6 ''' ''' 解题思路: 1. 使用分治法将问题分解为两两合并,可以解决该题,效率可能不高。 ''' EXAMPLES = [( [ build_list_node(1, 4, 5), build_list_node(1, 3, 4), build_list_node(2, 6), ], build_list_node(1, 1, 2, 3, 4, 5, 6), )] class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: n = ListNode(0) temp = n node1 = l1 node2 = l2 while not (node1 is None and node2 is None):
Examples: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) OUtput: 7 -> 0 -> 8 Explanation: 342 + 465 = 807 ''' ''' 总结: 1. carry_node = r.next, carry_node = ListNode(0), r.next != carry_node ''' EXAMPLES = [ ( (build_list_node(2, 4, 3), build_list_node(5, 6, 4)), build_list_node(7, 0, 8), ), ] class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: r = ListNode(0) carry = 0 carry_node = r while l1 or l2 or carry != 0: v1 = l1.val if l1 else 0 v2 = l2.val if l2 else 0
Note: * Only constant extra memory is allowed. * You may not after the values in the list's nodes, only nodes itself may be changed. ''' ''' 解题思路: 1. 属于第24题的变种,在核心判断的位置处理一下就可以了。 ''' EXAMPLES = [ ( (build_list_node(1, 2, 3, 4, 5), 2), build_list_node(2, 1, 4, 3, 5), ), ( (build_list_node(1, 2, 3, 4, 5), 3), build_list_node(3, 2, 1, 4, 5), ), ] class Solution: def reverse(self, head): arrays = [] node = head while node:
Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. ''' ''' 解题思路: 1. 执行到第 n-1 时,交换第 n 个 ''' EXAMPLES = [(build_list_node(1, 2, 3, 4, 5), )] class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: node = head node_map = {} i = 0 while node: node_map[i] = node node = node.next i += 1 prev_node = node_map.get(i - n - 1)