Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL :param head: :param m: :param n: :return: """ if not head or m == n: return head p = dummy = ListNode(0) dummy.next = head for i in range(m - 1): p = p.next tail = p.next for i in range(n - m): tmp = p.next p.next = tail.next tail.next = tail.next.next p.next.next = tmp return dummy.next if __name__ == '__main__': nums = [1, 2, 3, 4, 5] ln = create_listnode(nums) show_listnode(ln) s = Solution() ln = s.reverseBetween(ln, 1, 5) show_listnode(ln)
tail = ListNode(0) while stack1 or stack2: if stack1: s += stack1.pop().val if stack2: s += stack2.pop().val tail.val = int(s % 10) tmp = ListNode(int(s // 10)) tmp.next = tail tail = tmp s /= 10 return tail if tail.val != 0 else tail.next if __name__ == '__main__': """ 正常 9, 0 进一位 1, 9 进两位 22, 78 进N位 3334, 6666 """ s = Solution() nums1 = [2, 2] nums2 = [7, 8] ln1 = create_listnode(nums1) ln2 = create_listnode(nums2) show_listnode(ln1) show_listnode(ln2) show_listnode(s.addTwoNumbers2(ln1, ln2))
def removeElements3(self, head: ListNode, val: int) -> ListNode: """ recursive :param head: :param val: :return: """ if not head: return head head.next = self.removeElements2(head.next, val) return head if head.val != val else head.next if __name__ == '__main__': s = Solution() nums = [1, 2, 3] val = 2 list_nodes = create_listnode(nums) show_listnode(list_nodes) list_nodes = s.removeElements1(list_nodes, val) show_listnode(list_nodes) list_nodes = create_listnode(nums) list_nodes = s.removeElements2(list_nodes, val) show_listnode(list_nodes) list_nodes = create_listnode(nums) list_nodes = s.removeElements3(list_nodes, val) show_listnode(list_nodes)
from DataStructure.ListNode import ListNode, create_listnode, show_listnode class Solution: def insertionSortList(self, head: ListNode) -> ListNode: p = dummy = ListNode(0) curr = dummy.next = head while curr and curr.next: val = curr.next.val if curr.val <= val: curr = curr.next continue if p.next.val > val: p = dummy while p.next.val <= val: p = p.next tmp = curr.next curr.next = tmp.next tmp.next = p.next # 不是 tmp.next = curr e.g. [4, 4, 3, 2, 1] p.next = tmp return dummy.next if __name__ == '__main__': s = Solution() nums = [4, 3, 2, 1] list_node = create_listnode(nums) show_listnode(list_node) ans = s.insertionSortList(list_node) show_listnode(ans)