def reverseKGroup(self, head, k): if k < 2: return head fh = ListNode(0) fh.next = head pre, cur = fh, head while cur: count = 1 while cur.next and count < k: count += 1 cur = cur.next if count < k: break before = pre.next pre.next = cur pre = before after = before.next pre.next = cur.next while before != cur: t = after.next after.next = before before = after after = t cur = pre.next return fh.next
def swapPairs(self, head): pre = ListNode(0) pre.next = head cur = head head = pre while cur and cur.next: pre.next = cur.next cur.next = pre.next.next pre.next.next = cur pre = cur cur = cur.next return head.next
def deleteDuplicates(self, head): fh = ListNode(0) fh.next = head pre, cur = fh, head while cur: after = cur.next while after and after.val == cur.val: after = after.next if after == cur.next: pre = cur else: pre.next = after cur = after return fh.next
def insertionSortList(self, head): if not head: return head fh = ListNode(0) fh.next = head cur = head while cur.next: if cur.next.val < cur.val: pre = fh while pre.next.val < cur.next.val: pre = pre.next t = cur.next cur.next = t.next t.next = pre.next pre.next = t else: cur = cur.next return fh.next
def reverseBetween(self, head, m, n): if m == n: return head fh = ListNode(0) fh.next = head pre, cur = fh, head count = 1 while count < m: pre = cur cur = cur.next count += 1 t, h = cur, cur cur = cur.next while count < n: after = cur.next cur.next = h h = cur cur = after count += 1 pre.next = h t.next = cur return fh.next
def swapNodes(self, head: ListNode, k: int) -> ListNode: dummy = ListNode() dummy.next = head total = 0 cur = dummy while cur.next: cur = cur.next total += 1 lfast, lslow = head, dummy c = k - 1 while c: lfast = lfast.next lslow = lslow.next c -= 1 rfast, rslow = head, dummy c = total - k while c: rfast = rfast.next rslow = rslow.next c -= 1 if lfast.next == rfast: rnext = rfast.next lslow.next = rfast rfast.next = lfast lfast.next = rnext elif rfast.next == lfast: lnext = lfast.next rslow.next = lfast lfast.next = rfast rfast.next = lnext else: lnext = lfast.next rnext = rfast.next lslow.next = rfast rfast.next = lnext rslow.next = lfast lfast.next = rnext return dummy.next