while slow and fast: slow = slow.next fast = fast.next return slow def removeKthFromEnd(self, head, k): fast = head slow = head pre = None i = k while i > 0: fast = fast.next i = i-1 if fast==None: head = slow.next return head while fast!=None: pre = slow slow = slow.next fast = fast.next pre.next = slow.next slow.next = None return head head = construct_List_I([1, 2, 3, 4, 5]) solu = Solution() print(solu.findKthFromEnd(head, 5).val) print(travel_List(head))
while cur1 and cur2: if cur1.val <= cur2.val: cur.next = cur1 cur = cur1 cur1 = cur1.next else: cur.next = cur2 cur = cur2 cur2 = cur2.next while cur1: cur.next = cur1 cur = cur1 cur1 = cur1.next while cur2: cur.next = cur2 cur = cur2 cur2 = cur2.next cur.next = None return head from utils import construct_List_I, travel_List l1 = construct_List_I([1, 2, 4]) l2 = construct_List_I([1, 3, 4]) solu = Solution() l3 = solu.mergeTwoLists(l1, l2) print(travel_List(l3))
while i < m: if cur == None: return root pre_head = cur cur = cur.next i += 1 # pre_head为第m-1个节点,cur为第m个节点,此时i=m reverse_start = cur reverse_end = cur cur = cur.next while i < n: next = cur.next cur.next = reverse_start reverse_start = cur cur = next i += 1 reverse_end.next = cur if pre_head == None: return reverse_start else: pre_head.next = reverse_start return root root = construct_List_I([1, 2, 3, 4, 5, 6]) solu = Solution() root = solu.reverseList_II(root, 1, 6) print(solu.travelList(root))
class Solution: def deleteNode(self, cur): # 题目237 cur.val = cur.next.val cur.next = cur.next.next def removeElements(self, root, val): # 题目203 cur = root pre = None while cur != None: if cur.val == val: if pre == None: root = cur.next cur = cur.next else: pre.next = cur.next cur = cur.next else: pre = cur cur = cur.next return root head = construct_List_I([1, 2, 1, 4, 1]) solu = Solution() head = solu.removeElements(head, 1) print(travel_List(head))
else: pre = cur cur = cur.next return root def deleteDuplicates(self, head): ''' 第一个重复点保留,后面的重复点都删除 输入: 1->1->2->3->3 输出: 1->2->3 ''' pre = None cur = head while cur: if pre and pre.val == cur.val: while pre and cur: if pre.val == cur.val: cur = cur.next else: break pre.next = cur else: pre = cur cur = cur.next return head slou = Solution() root = construct_List_I([2, 2, 4, 4, 4]) root = slou.deleteDuplicates(root) print(travel_List(root))