def(self, head: ListNode, k: int) -> ListNode: ifnot head: returnNone cur = head cnt = 0 stack = [] while cur and len(stack) < k: stack.append(cur) cur = cur.next if len(stack) < k: return head newhead = stack.pop() res = newhead while stack: newhead.next = stack.pop() newhead = newhead.next newhead.next = self.reverseKGroup(cur, k) return res
defreverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ cur = head prev = None for i in range(m - 1): prev = cur cur = cur.next tail = cur r = None for i in range(n - m + 1): n = cur.next cur.next = r r = cur cur = n tail.next = n if prev: prev.next = r if m == 1: return r return head
Note: Remember to set large.next = None after the iteration. Or there might be cycle in the returned linked list!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defpartition(self, head: ListNode, x: int) -> ListNode: small_head, large_head = ListNode(0), ListNode(0) small, large = small_head, large_head cur = head while cur: if cur.val < x: small.next = cur small = small.next if cur.val >= x: large.next = cur large = large.next cur = cur.next large.next = None small.next = large_head.next return small_head.next
defnextLargerNodes(self, head): stack = [] # [[0,2]] index = 0 d = collections.defaultdict(int) while head: while stack and stack[-1][1] < head.val: v = stack.pop() d[v[0]] = head.val stack.append([index, head.val]) index += 1 head = head.next res = [0] * index for i in range(len(res)): res[i] = d[i] return res
近期评论