from ListNode import ListNode, create_list


class Solution:
    def reverseKGroup(self, head, k):
        dummy = jump = ListNode(0)
        dummy.next = save_head = head

        while True:
            count = 0
            while head and count < k:  # use r to locate the range
                head = head.next
                count += 1
            if count == k:  # if size k satisfied, reverse the inner linked list
                pre, cur = head, save_head
                for _ in range(k):
                    cur.next, cur, pre = pre, cur.next, cur  # standard reversing
                jump.next, jump, save_head = pre, save_head, head  # connect two k-groups
            else:
                return dummy.next


Solution().reverseKGroup(create_list(1, 2, 3, 4, 5, 6), 3).print_all()
from ListNode import ListNode, create_list


class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        sentinel = ListNode(101, head)
        pred = sentinel
        while head:
            if head.next and head.val == head.next.val:
                while head.next and head.val == head.next.val:
                    head = head.next
                pred.next = head.next
            else:
                pred = head
            head = head.next
        return sentinel.next


Solution().deleteDuplicates(create_list(1, 2, 3, 4, 4, 5)).print_all()
Example #3
0
from ListNode import ListNode, print_list, create_list

def remove_dups(head: ListNode) -> ListNode:
    """
    Write code to remove duplicates from an unsorted linked list.
    How would you solve this problem if a temporary buffer is not allowed?
    """

    p1 = head

    while p1:
        p2 = p1
        while p2.next:
            if p2.next.val == p1.val:
                p2.next = p2.next.next
            else:
                p2 = p2.next
        p1 = p1.next

    return head

print_list(remove_dups(create_list((3,3,6,4,4,5,6))))
Example #4
0
        # Recursively form a BST out of linked list from l --> r
        def convert(l, r):
            nonlocal head

            # Invalid case
            if l > r:
                return None

            mid = (l + r) // 2

            # First step of simulated inorder traversal. Recursively form
            # the left half
            left = convert(l, mid - 1)

            # Once left half is traversed, process the current node
            node = TreeNode(head.val)
            node.left = left

            # Maintain the invariance mentioned in the algorithm
            head = head.next

            # Recurse on the right hand side and form BST out of them
            node.right = convert(mid + 1, r)
            return node

        return convert(0, size - 1)


Solution().sortedListToBST(create_list(1, 2, 3, 4, 5)).print_all()
Example #5
0
        # for index, i in enumerate(lists):
        #     if i:
        #         q.put((i.val, index, i))
        # while not q.empty():
        #     _, index, head.next = q.get()
        #     head = head.next
        #     if head.next:
        #         q.put((head.next.val, index, head.next))
        # return sentinel.next

        # Using equivalent heap, faster
        sentinel = ListNode()
        head = sentinel
        q = []
        for index, i in enumerate(lists):
            if i:
                heapq.heappush(q, (i.val, index, i))
        while q:
            _, index, head.next = heapq.heappop(q)
            head = head.next
            if head.next:
                heapq.heappush(q, (head.next.val, index, head.next))
        return sentinel.next


a = create_list(1, 4, 5)
b = create_list(1, 3, 4)
c = create_list(2, 6)
l = [a, b, c]
Solution().mergeKLists(l).print_all()
Example #6
0
            slow = slow.next
        line2 = slow.next
        slow.next = None

        cur = line2
        prev = None
        while cur:
            # succ = cur.next
            # cur.next = prev
            # prev = cur
            # cur = succ

            # Concise notation
            cur.next, prev, cur = prev, cur, cur.next
        line2 = prev

        while line2:
            # temp = line2.next
            # line2.next = head.next
            # head.next = line2
            # head = head.next.next
            # line2 = temp

            # Concise notation
            line2.next, head.next, head, line2 = head.next, line2, head.next, line2.next
        sentinel.print_all()


if __name__ == '__main__':
    Solution().reorderList(create_list(1, 2, 3, 4, 5))
            curr.next = l1 if l1 else l2
            while curr.next:
                curr = curr.next  # Find tail
            # the returned tail should be the "dummy_start" node of next chunk
            return curr

        total_length = getSize(head)
        dummy = ListNode(0)
        dummy.next = head
        start, dummy_start, size = None, None, 1

        while size < total_length:
            dummy_start = dummy
            start = dummy.next
            while start:
                left = start
                right = split(left,
                              size)  # start from left, cut with size=size
                start = split(right,
                              size)  # start from right, cut with size=size
                dummy_start = merge(
                    left, right,
                    dummy_start)  # returned tail = next dummy_start
            size *= 2
        return dummy.next


a = create_list(10, 1, 30, 2, 5)
Solution().sortList(a).print_all()
Example #8
0
from ListNode import ListNode, create_list


class Solution:
    def reverseBetween(self, head: ListNode, left: int,
                       right: int) -> ListNode:
        if left == right:
            return head
        sentinel = ListNode(0, head)
        l = sentinel
        for _ in range(left - 1):
            l = l.next
        prev = l
        r = l.next
        for _ in range(right - left):
            r.next, r, prev = prev, r.next, r
        l.next.next = r.next
        l.next = r
        r.next = prev
        return sentinel.next


Solution().reverseBetween(create_list(1, 2, 3, 4, 5), 2, 4).print_all()
from ListNode import ListNode, create_list


class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        new_head = head
        if head.next:
            new_head = head.next
            head.next = new_head.next
            new_head.next = head
        while head.next and head.next.next:
            temp = head.next
            temp2 = head.next.next.next
            head.next = head.next.next
            head.next.next = temp
            temp.next = temp2
            head = temp
        return new_head


a = create_list([1, 2, 3, 4, 5])
Solution().swapPairs(a).print_all()
Example #10
0
from ListNode import ListNode, print_list, create_list


def delete_middle_node(node: ListNode):
    """
    Implement an algorithm to delete a node in the middle of
    a singly linked list, given only access to that node
    """

    node.val = node.next.val
    node.next = node.next.next


ll = create_list((1, 2, 3, 4, 5))
ll = ll.next
delete_middle_node(ll)
Example #11
0
from ListNode import ListNode, create_list


class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        add_one = False
        sum_node = ListNode(0)
        savehead = sum_node
        while l1 or l2 or add_one:
            sum_node.next = ListNode(0)
            sum_node = sum_node.next
            if l1:
                sum_node.val += l1.val
                l1 = l1.next
            if l2:
                sum_node.val += l2.val
                l2 = l2.next
            if add_one:
                sum_node.val += 1
                add_one = False
            if sum_node.val >= 10:
                sum_node.val -= 10
                add_one = True
        return savehead.next


Solution().addTwoNumbers(create_list(2, 4, 3, 5), create_list(5, 6,
                                                              4)).print_all()
Example #12
0
from ListNode import ListNode, create_list


class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        init = head
        while head and head.next:
            if head.val == head.next.val:
                head.next = head.next.next
            else:
                head = head.next
        return init


if __name__ == '__main__':
    print(Solution().deleteDuplicates(create_list(1, 2, 3, 3, 4, 4, 5)))
Example #13
0
from ListNode import ListNode, print_list, create_list


def return_kth_to_last(head: ListNode, k: int) -> int:
    """
    Implement an algorithm to find the kth to last element of a singly linked list
    """

    p1 = head
    p2 = head
    for x in range(k):
        p2 = p2.next
    while p2:
        p1 = p1.next
        p2 = p2.next
    return p1.val


print(return_kth_to_last(create_list((3, 4, 5, 6, 7)), 3))
Example #14
0
from ListNode import ListNode, create_list


class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        sentinel = ListNode(next=head)
        cur = sentinel
        while cur:
            if cur.next and cur.next.val == val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return sentinel.next


if __name__ == '__main__':
    Solution().removeElements(create_list(7, 7, 7, 7), 7).print_all()