Ejemplo n.º 1
0
def swap_pairs(head):
    """
    Swap every two adjacent nodes in given linked list

    :param head: head node of given linked list
    :type head: ListNode
    :return: head node of swapped linked list
    :rtype: ListNode
    """
    # basic case
    if head is None:
        return head

    # dummy head
    dummy = ListNode(None)
    dummy.next = head

    # swap pairs
    curr = dummy
    while curr.next is not None and curr.next.next is not None:
        tmp_next = curr.next
        tmp_nnnext = curr.next.next.next
        curr.next = curr.next.next
        curr.next.next = tmp_next
        curr.next.next.next = tmp_nnnext
        curr = curr.next.next

    return dummy.next
Ejemplo n.º 2
0
def addTwoNumbers(l1, l2):
    """
    Reverse the lists and then sum
    Time: O(m+n), m the length of l1 and n the length of l2
    Space: O(m+n) since we have reversed the lists
    """
    addone = 0
    head = ListNode(-1)
    curr_node = head

    l1 = reverse_linked_list(l1)
    l2 = reverse_linked_list(l2)

    while l1 is not None or l2 is not None:
        if not l1:
            l1 = ListNode(0)
        elif not l2:
            l2 = ListNode(0)

        curr_sum = l1.val + l2.val + addone
        l1, l2 = l1.next, l2.next
        curr_node.next = ListNode(curr_sum % 10)
        curr_node = curr_node.next
        if curr_sum >= 10:
            addone = 1
        else:
            addone = 0

    if addone == 1:
        curr_node.next = ListNode(1)

    return reverse_linked_list(head.next)
Ejemplo n.º 3
0
 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
     carry = 0
     out = None
     currNode = None
     while not (l1 is None and l2 is None and carry == 0):
         currVal = 0
         if l1 is not None:
             currVal += l1.val
         if l2 is not None:
             currVal += l2.val
         if carry == 1:
             currVal += 1
             carry = 0
         if currVal >= 10:
             carry = 1
             currVal -= 10
         if out is None:
             currNode = ListNode(currVal)
             out = currNode
         else:
             currNode.next = ListNode(currVal)
             currNode = currNode.next
         if l1:
             l1 = l1.next
         if l2:
             l2 = l2.next
     return out
Ejemplo n.º 4
0
    def mergeKLists(self, lists):
        """
        用优先队列优化方法
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        # For python 2
        # from queue import PriorityQueue

        # For python 3
        from queue import PriorityQueue

        head = cur = ListNode(0)
        q = PriorityQueue()
        for l in lists:
            if l:
                q.put((l.val, l))
        while not q.empty():
            val, node = q.get()
            cur.next = ListNode(val)
            cur = cur.next
            node = node.next
            if node:
                q.put((node.val, node))
        return head.next
Ejemplo n.º 5
0
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        k = len(lists)
        res = ListNode(0)
        tail = res

        heap = []
        heapq.heapify(heap)

        for indx in range(k):
            if not lists[indx]: continue
            node = lists[indx]
            heapq.heappush(heap, (node.val, indx))
            lists[indx] = node.next

        while heap:
            item, indx = heapq.heappop(heap)
            tail.next = ListNode(item)
            tail = tail.next
            if lists[indx]:
                heapq.heappush(heap, (lists[indx].val, indx))
                lists[indx] = lists[indx].next

        return res.next
Ejemplo n.º 6
0
 def addTwoNumbers(self, l1, l2):
     """
     :type l1: ListNode
     :type l2: ListNode
     :rtype: ListNode
     """
     left_finish = right_finish = False
     first = result = ListNode(0)
     add = 0
     while True:
         if l1:
             left = l1.val
             l1 = l1.next
         else:
             left_finish = True
             left = 0
         if l2:
             right = l2.val
             l2 = l2.next
         else:
             right_finish = True
             right = 0
         if left_finish == right_finish == True and not add:
             break
         tmp = (left + right + add)
         if tmp >= 10:
             result.next = ListNode(tmp - 10)
             add = 1
         else:
             result.next = ListNode(tmp)
             add = 0
         result = result.next
     return first.next
Ejemplo n.º 7
0
def sort_list(head):
    def partition(start, end):
        node = start.next.next  # node to iterate
        first_pivot = start.next
        first_pivot.next = end  # Insert large node between pivot and end
        last_pivot = first_pivot
        while node != end:
            tmp = node.next
            if node.val > first_pivot.val:
                node.next = last_pivot.next
                last_pivot.next = node
            elif node.val < first_pivot.val:
                node.next = start.next
                start.next = node
            else:
                node.next = last_pivot.next
                last_pivot.next = node
                last_pivot = last_pivot.next
            node = tmp
        return [first_pivot, last_pivot]

    def qsort(start, end):
        if start.next != end:
            first_pivot, last_pivot = partition(start, end)
            qsort(start, first_pivot)
            qsort(last_pivot, end)

    head_pre = ListNode(0)
    head_pre.next = head
    qsort(head_pre, None)
    return head_pre.next
Ejemplo n.º 8
0
def add_two_numbers(l1, l2):
    """
    Add two integers represented in linked lists

    :param l1: head of first linked list
    :type l1: ListNode
    :param l2: head of second linked list
    :type l2: ListNode
    :return: head of result linked list
    :rtype: ListNode
    """
    result_dummy = ListNode(None)
    result = result_dummy
    carry = 0
    while l1 is not None or l2 is not None or carry != 0:
        v1 = l1.val if l1 is not None else 0
        v2 = l2.val if l2 is not None else 0
        val = (v1 + v2 + carry) % 10
        carry = (v1 + v2 + carry) // 10
        result.next = ListNode(val)
        result = result.next
        if l1 is not None:
            l1 = l1.next
        if l2 is not None:
            l2 = l2.next
    return result_dummy.next
Ejemplo n.º 9
0
def delete_duplicates(head):
    """
    Remove all duplicates in given linked list, leaving only distinct numbers

    :param head: head node of given linked list
    :type head: ListNode
    :return: head node of operated linked list
    :rtype: ListNode
    """
    if head is None:
        return head

    dummy_head = ListNode(None)
    dummy_head.next = head
    curr = dummy_head

    while curr.next is not None and curr.next.next is not None:
        if curr.next.val == curr.next.next.val:
            val = curr.next.val
            while curr.next is not None and curr.next.val == val:
                tmp = curr.next
                curr.next = curr.next.next
                del tmp
        else:
            curr = curr.next

    return dummy_head.next
Ejemplo n.º 10
0
    def addAtIndex(self, index: int, val: int) -> None:
        """
        Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
        """
        # If index is greater than the length,
        # the node will not be inserted.
        if index > self.size:
            return

        # [so weird] If index is negative,
        # the node will be inserted at the head of the list.
        if index < 0:
            index = 0

        self.size += 1
        # find predecessor of the node to be added
        pred = self.head
        for _ in range(index):
            pred = pred.next

        # node to be added
        to_add = ListNode(val)
        # insertion itself
        to_add.next = pred.next
        pred.next = to_add
Ejemplo n.º 11
0
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        """
        Time: O(max(m, n))
        Space: O(max(m, n))
        """
        dummy = ListNode(0)
        current = dummy

        carry = 0
        while l1 or l2:
            num = carry
            num += l1.val if l1 else 0
            num += l2.val if l2 else 0

            carry = num // 10
            num %= 10

            current.next = ListNode(num)
            current = current.next

            if l1 is not None:
                l1 = l1.next
            if l2 is not None:
                l2 = l2.next

        if carry == 1:
            current.next = ListNode(carry)

        return dummy.next
Ejemplo n.º 12
0
 def reverseBetween(self, head, m, n):
     """
     :type head: ListNode
     :type m: int
     :type n: int
     :rtype: ListNode
     """
     dummy = ListNode(-1)
     dummy.next = head
     pre = dummy
     # 找到翻转链表部分的前一个节点, 1->2->3->4->5->NULL, m = 2, n = 4 指的是 节点值为1
     for _ in range(m - 1):
         pre = pre.next
     # 用双指针,进行链表翻转
     node = None
     cur = pre.next
     for _ in range(n - m + 1):
         tmp = cur.next
         cur.next = node
         node = cur
         cur = tmp
     # 将翻转部分 和 原链表拼接
     pre.next.next = cur
     pre.next = node
     return dummy.next
Ejemplo n.º 13
0
def partition(head, x):
    """
    Partition a given linked list with given number

    :param head: head node of given linked list
    :type head: ListNode
    :param x: given number
    :type x: int
    :return: head node of operated linked list
    :rtype: ListNode
    """
    if head is None:
        return head

    left_dummy = ListNode(None)
    right_dummy = ListNode(None)
    left = left_dummy
    right = right_dummy

    curr = head
    while curr is not None:
        if curr.val < x:
            left.next = curr
            left = left.next
        else:
            right.next = curr
            right = right.next
        curr = curr.next
    right.next = None
    left.next = right_dummy.next

    return left_dummy.next
Ejemplo n.º 14
0
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        empty_head = ListNode()
        tail = empty_head
        carry = 0

        while l1 or l2:
            num = (l1.val if l1 else 0) + (l2.val if l2 else 0)

            if carry:
                num += 1
                carry = 0

            if num >= 10:
                carry = 1
                num -= 10

            tail.next = ListNode(num)
            tail = tail.next

            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next

        if carry:
            tail.next = ListNode(carry)

        return empty_head.next
def remove_elements(head, val):
    """
    Remove all elements from a linked list of integers that have value val.

    :param head: head node of given linked list
    :type head: ListNode
    :param val: value to remove
    :type val: int
    :return: head node of removed linked list
    :rtype: ListNode
    """
    # basic case
    if head is None:
        return head

    # dummy head
    dummy = ListNode(None)
    dummy.next = head

    # traverse to remove nodes with given value
    curr = dummy
    while curr is not None:
        while curr.next is not None and curr.next.val == val:
            tmp = curr.next
            curr.next = curr.next.next
            del tmp
        curr = curr.next

    return dummy.next
Ejemplo n.º 16
0
def insertion_sort_list(head):
    """
    Sort a linked list by insertion sort

    :param head: head node of given linked list
    :type head: ListNode
    :return: head node of sorted linked list
    :rtype: ListNode
    """
    dummy = ListNode(None)
    dummy.next = head

    curr = head
    while curr is not None:
        if curr.next is not None and curr.next.val < curr.val:
            # find insertion position
            pre = dummy
            while pre.next is not None and pre.next.val < curr.next.val:
                pre = pre.next
            # insert the next node of curr to the position after node pre
            tmp = pre.next
            pre.next = curr.next
            curr.next = curr.next.next
            pre.next.next = tmp
        else:
            curr = curr.next
    return dummy.next
Ejemplo n.º 17
0
def swapPairs_loop(head):
    """
    Loop
    Time: O(n) (but in runtime slower than recursion)
    Space: O(1) (but in runtime similar to recursion)
    """
    # dummy head for return
    start = ListNode(-1)
    start.next = head
    # var to contain the previous node
    prev_node = start
    # stop the loop if only one or zero node left
    while head and head.next:
        # the current two nodes to be swapped
        first_node = head
        second_node = head.next

        # swap, and linked the second node in the pair to the previous node
        prev_node.next = second_node
        first_node.next = second_node.next
        second_node.next = first_node

        # update previous node to the next pair
        # update head to the first node in the next pair
        prev_node = first_node
        head = first_node.next

    return start.next
def remove_nth_from_end(head, n):
    """
    Remove the n-th node from the end of list

    :param head: head node of given linked list
    :type head: ListNode
    :param n: order n
    :type n: int
    :return: head node of operated linked list
    :rtype: ListNode
    """
    # basic case
    if head is None:
        return head

    # initialize variables
    dummy = ListNode(None)
    dummy.next = head
    slow = fast = dummy

    # slow pointer is slower than fast pointer by n positions
    count = 0
    while fast.next is not None:
        fast = fast.next
        count += 1
        if count > n:
            slow = slow.next

    # if need to remove node
    if count >= n:
        tmp = slow.next
        slow.next = slow.next.next
        del tmp

    return dummy.next
Ejemplo n.º 19
0
 def addTwoNumbers(self, l1, l2):
     """
     :type l1: ListNode
     :type l2: ListNode
     :rtype: ListNode
     """
     p1 = l1
     p2 = l2
     head = tail = None
     r = 0
     while p1 or p2:
         p1_next = p1.next if p1 else None
         p2_next = p2.next if p2 else None
         val = (p1.val if p1 else 0) + (p2.val if p2 else 0) + r
         if val >= 10:
             val -= 10
             r = 1
         else:
             r = 0
         node = ListNode(val)
         if head is None:
             head = tail = node
         else:
             tail.next = node
             tail = node
         p1 = p1_next
         p2 = p2_next
     if r:
         node = ListNode(r)
         tail.next = node
     return head
Ejemplo n.º 20
0
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        """
        Iterate from the right digits
        Create dummy node root and copy pointer to it
        While there are some nodes or transfer digit:
        Calculate sum of node values and transfer digit
        Create linked node with remainder to 10
        Set transfer with quotient to 10
        Link each node to next one
        Return dummy node next
        """
        transfer = 0
        root = ListNode()
        node = root

        while l1 or l2 or transfer:
            first = l1.val if l1 else 0
            second = l2.val if l2 else 0

            _sum = first + second + transfer
            node.next = ListNode(_sum % 10)
            transfer = _sum // 10
            node = node.next

            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None

        return root.next
def deleteDuplicates_last(head):
    """
    Remove all duplicates but the last and finally itself
    Time: O(n)
    Space: O(1)
    """
    if not head:
        return head

    # setup the pseudo head
    return_head = ListNode(-1)
    return_head.next = head
    # prev_node is last the non-duplicate node
    prev_node = return_head

    # head could be None here
    while head and head.next:

        if head.val == head.next.val:
            # keep on moving forward until head is now the last occurrence
            while head.next and head.val == head.next.val:
                head = head.next
            # skip the last occurrence, NOTE: the new head could be None
            head = head.next
            prev_node.next = head

        else:
            prev_node = head
            head = head.next

    return return_head.next
 def mergeTwoLists(self, l1, l2):
     """
     合并两个有序链表
     :type l1: ListNode
     :type l2: ListNode
     :rtype: ListNode
     """
     t1 = l1
     t2 = l2
     cur = head = ListNode(0)
     while t1 or t2:
         if not t1:
             cur.next = ListNode(t2.val)
             t2 = t2.next
         elif not t2:
             cur.next = ListNode(t1.val)
             t1 = t1.next
         elif t1.val < t2.val:
             cur.next = ListNode(t1.val)
             t1 = t1.next
         else:
             cur.next = ListNode(t2.val)
             t2 = t2.next
         cur = cur.next
     return head.next
Ejemplo n.º 23
0
 def insert(pre, cur, val):
     nonlocal res
     new_node = ListNode(val)
     if not pre:
         res = new_node
     else:
         pre.next = new_node
     new_node.next = cur
Ejemplo n.º 24
0
Archivo: 25.py Proyecto: SS4G/JP2020
 def reverseKGroup(self, head, k):
     """
     :type head: ListNode
     :type k: int
     :rtype: ListNode
     """
     head_node = ListNode(0)
     head_node.next = head
Ejemplo n.º 25
0
Archivo: 25.py Proyecto: SS4G/JP2020
 def reverseK(head_node, k):
     dummpy_node = ListNode(0)
     dummpy_node.next = head_node
     tmp_ptr = dummpy_node
     for i in range(k):
         tmp_ptr = tmp_ptr.next
         if i < k - 1 and tmp_ptr is None:
             return dummpy_node.next
Ejemplo n.º 26
0
def generate_sll_from_list(values):
    D = c = ListNode(0)

    for v in values:
        c.next = ListNode(v)
        c = c.next

    res, D.next = D.next, None
    return res
Ejemplo n.º 27
0
 def removeElements(self, head, val):
     prev = ListNode(0)
     prev.next = head
     cur = prev
     while cur.next:
         if cur.next.val == val:
             cur.next = cur.next.next
         else:
             cur = cur.next
     return prev.next
Ejemplo n.º 28
0
 def copy(raw):
     if raw in cache:
         return cache[raw]
     new = Node(raw.val)
     cache[raw] = new
     if raw.next:
         new.next = copy(raw.next)
     if raw.random:
         new.random = copy(raw.random)
     return new
Ejemplo n.º 29
0
 def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
     if l1 is None:
         return l2
     elif l2 is None:
         return l1
     elif l1.val < l2.val:
         l1.next = self.mergeTwoLists(l1.next, l2)
         return l1
     else:
         l2.next = self.mergeTwoLists(l1, l2.next)
         return l2
Ejemplo n.º 30
0
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        pre_head = ListNode(None)
        pre_head.next = head
        pre_node = pre_head

        last_node = self._move(pre_node, k)
        while last_node:
            next_k = last_node.next
            pre_node = self._reverse_sub_list_node(pre_node, next_k, k)
            last_node = self._move(next_k, k - 1)
        return pre_head.next
Ejemplo n.º 31
0
 def helper(l1, l2, offset):
     if l1 is None:
         return None
     if offset == 0:
         result = ListNode(l1.val + l2.val)
         post = helper(l1.next, l2.next, 0)
     else:
         result = ListNode(l1.val)
         post = helper(l1.next, l2, offset-1)
     if post is not None and post.val > 9:
         result.val += 1
         post.val -= 10
     result.next = post
     return result
Ejemplo n.º 32
0
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """

        def get_len(l):
            count = 0
            while l is not None:
                l = l.next
                count += 1
            return count

        def helper(l1, l2, offset):
            if l1 is None:
                return None
            if offset == 0:
                result = ListNode(l1.val + l2.val)
                post = helper(l1.next, l2.next, 0)
            else:
                result = ListNode(l1.val)
                post = helper(l1.next, l2, offset-1)
            if post is not None and post.val > 9:
                result.val += 1
                post.val -= 10
            result.next = post
            return result

        size1 = get_len(l1)
        size2 = get_len(l2)

        head = ListNode(1)
        if size1 < size2:
            head.next = helper(l2, l1, size2 - size1)
        else:
            head.next = helper(l1, l2, size1 - size2)
        if head.next.val > 9:
            head.next.val -= 10
            return head
        else:
            return head.next
Ejemplo n.º 33
0
    def merge_sort(self, head, n):  # non recursive

        def split(p, step):
            last = None
            for i in xrange(step):
                if p is None:
                    break
                last = p
                p = p.next
            if last:
                last.next = None
            return p

        def merge(h1, h2, tail):
            p1, p2 = h1, h2
            while p1 or p2:
                if not p2 or p1 and p1.val <= p2.val:
                    tail.next = p1
                    tail = p1
                    p1 = p1.next
                elif not p1 or p2 and p2.val <= p1.val:
                    tail.next = p2
                    tail = p2
                    p2 = p2.next
                else:
                    break
            return tail

        dummy = ListNode(0)
        dummy.next = head
        left = right = tail = None
        step = 1
        while step < n:
            p = dummy.next
            tail = dummy
            while p:
                left = p
                right = split(p, step)
                p = split(right, step)
                tail = merge(left, right, tail)
            step <<= 1
        return dummy.next
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        if head is None:
            return head

        fake_head = ListNode(0)
        fake_head.next = head

        p,q,r = fake_head,head,head.next

        while q and r:
            p.next = r
            q.next = r.next
            r.next = q

            p = q
            q = p.next
            r = q.next if q else None
        
        return fake_head.next
__author__ = 'clp'

from utils import ListNode

class Solution(object):

    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        while head is not None and head.val == val:
            head = head.next
        if not head:
            return None
        current_node = head
        while current_node.next:
            if current_node.next.val == val:
                current_node.next = current_node.next.next
            else:
                current_node = current_node.next
        return head

if __name__ == '__main__':
    ListNode.print_linked_list(Solution().removeElements(ListNode.build_linked_list([1,2,3,4,5,6]),  6))
    ListNode.print_linked_list(Solution().removeElements(ListNode.build_linked_list([1,1,3,4,56]),  1))
    ListNode.print_linked_list(Solution().removeElements(ListNode.build_linked_list([2,1,3,4,4,4,4]),  4))
    ListNode.print_linked_list(Solution().removeElements(ListNode.build_linked_list([1]),  1))
Ejemplo n.º 36
0
        :rtype: bool
        """
        slow = fast = head
        while fast:
            slow = slow.next
            fast = fast.next.next if fast.next else None
        # slow is head of right half now, reverse right half
        p, last = slow, None
        while p:
            next = p.next
            p.next = last
            last = p
            p = next
        # compare left half and right half
        p1, p2 = head, last
        while p1 and p2:
            if p1.val != p2.val:
                return False
            p1 = p1.next
            p2 = p2.next
        return True


if __name__ == '__main__':
    from utils import ListNode
    f = Solution().isPalindrome
    assert f(ListNode.make_list([1, 2, 3, 2, 1]))
    assert f(ListNode.make_list([1, 2, 2, 1]))
    assert not f(ListNode.make_list([1, 2, 1, 1]))
    assert not f(ListNode.make_list([1, 2, 3, 1, 1]))
Ejemplo n.º 37
0
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        if not head:
            return None

        global new_head

        def reverse_list(node):
            global new_head
            if node.next is None:
                new_head = node
                return node
            next_node = reverse_list(node.next)
            next_node.next = node
            return node

        reverse_list(head)
        head.next = None
        return new_head


if __name__ == '__main__':
    l = ListNode.build_linked_list([])
    l = ListNode.build_linked_list([1])
    # l = ListNode.build_linked_list([1, 2, 3, 4, 5])
    ListNode.print_linked_list(Solution().reverseList(l))
            return node

        lA, lB = link_len(headA), link_len(headB)
        if lA > lB:
            hA, hB = link_index(headA, lA - lB), headB
        elif lA < lB:
            hA, hB = headA, link_index(headB, lB - lA)
        else:
            hA, hB = headA, headB

        nA, nB = hA, hB
        while nA and nB:
            if nA == nB:
                return nA
            nA = nA.next
            nB = nB.next
        return None


if __name__ == '__main__':
    headC = ListNode.build_linked_list([4,5,6])
    headA = ListNode(1)
    headA.next = ListNode(2)
    headA.next.next = headC
    headB = headC

    print Solution().getIntersectionNode(headA, headB)
    print Solution().getIntersectionNode(None, None)
    print Solution().getIntersectionNode(ListNode.build_linked_list([1,3,5,7,9,11,13,15,17,19,21]),
                                         ListNode.build_linked_list([2]))
Ejemplo n.º 39
0
        @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node.
        :type head: ListNode
        """
        self.head = head

    def getRandom(self):
        """
        Returns a random node's value.
        :rtype: int
        """
        # Reservoir Sampling
        p = self.head
        result = None
        i = 0
        while p:
            if random.randint(0, i) == 0:
                result = p.val
            i += 1
            p = p.next
        return result


if __name__ == '__main__':
    from utils import ListNode
    s = Solution(ListNode.make_list([1, 2, 3, 4]))
    print s.getRandom()
    print s.getRandom()
    print s.getRandom()
    print s.getRandom()
Ejemplo n.º 40
0
        i = 1
        p = head
        last = None
        while i < m:
            last = p
            p = p.next
            i += 1
        rhead = p
        rlast = None
        while p and i <= n:
            next = p.next
            p.next = rlast
            rlast = p
            p = next
            i += 1
        rhead.next = p
        if m > 1:
            last.next = rlast
        else:
            head = rlast
        return head


if __name__ == '__main__':
    from utils import ListNode
    f = Solution().reverseBetween
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 2, 4)
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 2, 5)
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 1, 5)
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 1, 4)
        :rtype: ListNode
        """
        if not head:
            return None
        hash_counter = {}
        current = head
        while current:
            k = current.val
            hash_counter[k] = hash_counter.get(k, 0) + 1
            current = current.next
        new_head = None
        prev, current = None, head
        while current:
            if hash_counter[current.val] >= 2:
                if prev:
                    prev.next = current.next
                prev, current = prev, current.next
            else:
                if not new_head:
                    new_head = current
                prev, current = current, current.next
        return new_head


if __name__ == '__main__':
    ListNode.print_linked_list(Solution().deleteDuplicates(ListNode.build_linked_list([1,1,2,3,1,1,2])))
    ListNode.print_linked_list(Solution().deleteDuplicates(ListNode.build_linked_list([1,1,2,3,1,1])))
    ListNode.print_linked_list(Solution().deleteDuplicates(ListNode.build_linked_list([1,2,3,3,4,4,5])))
    ListNode.print_linked_list(Solution().deleteDuplicates(ListNode.build_linked_list([1, 5])))
    ListNode.print_linked_list(Solution().deleteDuplicates(ListNode.build_linked_list([1])))
    ListNode.print_linked_list(Solution().deleteDuplicates(ListNode.build_linked_list([])))
Ejemplo n.º 42
0
        current = head
        while current:
            if current.val < x:
                if not f_head:
                    f_head = current
                    f_end = f_head
                else:
                    f_end.next = current
                    f_end = f_end.next
            else:
                if not b_head:
                    b_head = current
                    b_end = b_head
                else:
                    b_end.next = current
                    b_end = b_end.next
            current = current.next
        if f_head:
            f_end.next = b_head
        if b_end:
            b_end.next = None
        return f_head if f_head else b_head

if __name__ == '__main__':
    ListNode.print_linked_list(Solution().partition(ListNode.build_linked_list([1, 4, 3, 2, 5, 2]), 3))
    ListNode.print_linked_list(Solution().partition(ListNode.build_linked_list([1, 4, 3, 2, 5, 2]), 6))
    ListNode.print_linked_list(Solution().partition(ListNode.build_linked_list([1, 4, 3, 2, 5, 2]), 1))
    ListNode.print_linked_list(Solution().partition(ListNode.build_linked_list([1, 4, 3, 2, 5, 2]), 2))
    ListNode.print_linked_list(Solution().partition(ListNode.build_linked_list([1]), 2))
    ListNode.print_linked_list(Solution().partition(None, 2))
Ejemplo n.º 43
0
            node = p.__class__(p.val)
            if tail and node.val > tail.val:
                tail = self.insert(tail, tail, node)
            else:
                tail = self.insert(new_head, tail, node)
            p = p.next
        return new_head.next

    def insert(self, head, tail, node):
        current = head.next
        last = head
        while current:
            if current.val > node.val:
                break
            last = current
            current = current.next
        if last:
            last.next = node
        node.next = current
        return node if current is None else tail


if __name__ == "__main__":
    from datetime import datetime
    from utils import ListNode
    head = ListNode.make_list([3, 2, 1])
    st = datetime.now()
    p = Solution().insertionSortList(head)
    # print p.to_list()
    print datetime.now() - st
Ejemplo n.º 44
0
        """
        p = head
        less_head = less_tail = None
        greater_head = greater_tail = None
        while p:
            if p.val < x:
                if less_head is None:
                    less_head = less_tail = p
                else:
                    less_tail.next = p
                    less_tail = p
            else:
                if greater_head is None:
                    greater_head = greater_tail = p
                else:
                    greater_tail.next = p
                    greater_tail = p
            p = p.next
        if greater_tail:
            greater_tail.next = None
        if less_tail:
            less_tail.next = greater_head
        return less_head or greater_head


if __name__ == '__main__':
    f = Solution().partition
    from utils import ListNode
    print f(ListNode.make_list([1, 4, 3, 2, 5, 2]), 3)
    print f(ListNode.make_list([1]), 0)
Ejemplo n.º 45
0
        h2 = self.merge_sort(head2, n - n / 2)
        p1, p2 = h1, h2
        h = t = None
        while p1 or p2:
            if not p2 or p1 and p1.val <= p2.val:
                if h is None:
                    h = t = p1
                else:
                    t.next = p1
                    t = p1
                p1 = p1.next
            elif not p1 or p2 and p2.val <= p1.val:
                if h is None:
                    h = t = p2
                else:
                    t.next = p2
                    t = p2
                p2 = p2.next
            else:
                break
        return h


if __name__ == '__main__':
    f = Solution().sortList
    from utils import ListNode
    print f(ListNode.make_list([3, 4, 2, 1, 7, 5, 6]))
    print f(ListNode.make_list([1]))
    print f(ListNode.make_list([5, 4, 3]))
    print f(ListNode.make_list([4,19,14,5,-3,1,8,5,11,15]))
Ejemplo n.º 46
0
#
#   This is very tricky, see proof in Gossip.md
#

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        slow = fast = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                slow = head
                while fast != slow:
                    fast = fast.next
                    slow = slow.next
                return slow
        return None


if __name__ == '__main__':
    head = ListNode.build_linked_list([1,2,3,4,5])
    head.next.next.next.next.next = head.next.next
    print Solution().detectCycle(head).val
    print Solution().detectCycle(None)


Ejemplo n.º 47
0
        slow.next = None
        prev.next = None
        # reverse the list from the mid
        while current:
            next = current.next
            current.next = prev
            prev, current = current, next
        # interleave the two list
        current1, current2 = head, prev
        while current1 and current2:
            current1_next, current2_next = current1.next, current2.next
            current1.next, current2.next = current2, current1_next
            current1, current2 = current1_next, current2_next

if __name__ == '__main__':
    l1 = ListNode.build_linked_list([1,2,3])
    Solution().reorderList(l1)
    ListNode.print_linked_list(l1)
    l1 = ListNode.build_linked_list([1,2])
    Solution().reorderList(l1)
    ListNode.print_linked_list(l1)
    l1 = ListNode.build_linked_list([])
    Solution().reorderList(l1)
    ListNode.print_linked_list(l1)
    l1 = ListNode.build_linked_list([1])
    Solution().reorderList(l1)
    ListNode.print_linked_list(l1)
    l1 = ListNode.build_linked_list([1,2,3,4,5,6])
    Solution().reorderList(l1)
    ListNode.print_linked_list(l1)
    l1 = ListNode.build_linked_list([1,2,3,4,5,6,7])
class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def deleteDuplicates(self, head):
        if head is None:
            return head
        new_head = head.__class__(0)
        new_head.next = head
        pre_last = new_head
        last = head
        current = head.next
        last_delete = None
        while current:
            if current.val == last.val:
                pre_last.next = current.next
                last_delete = current.val
            else:
                if last_delete != last.val:
                    pre_last = last
                last = current
            current = current.next
        return new_head.next


if __name__ == "__main__":
    from utils import ListNode
    head = ListNode.make_list([1, 1, 2, 2])
    p = Solution().deleteDuplicates(head)
    print p
Ejemplo n.º 49
0
                last = p
                p = next
            return last, head, p

        if k <= 1:
            return head
        result = None
        last = None
        p = head
        while p:
            new_head, new_tail, next = reverse(p, k)
            if p is head:
                result = new_head
            if last:
                last.next = new_head
            last = new_tail
            p = next
        return result


if __name__ == '__main__':
    from utils import ListNode
    f = Solution().reverseKGroup
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 2)
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 3)
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 1)
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 0)
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 4)
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 5)
    print f(ListNode.make_list([1, 2, 3, 4, 5]), 6)
Ejemplo n.º 50
0
        # count the length and get last_node
        length = 0
        current = head
        while current:
            length += 1
            if current.next is None:
                last_node = current
            current = current.next
        k = k % length
        if k == 0:
            return head
        idx = 0
        current = head
        while current:
            if idx == length - k - 1:
                target_prev, target_current = current, current.next
            current = current.next
            idx += 1
        new_head = target_current
        last_node.next = head
        target_prev.next = None
        return new_head

if __name__ == '__main__':
    ListNode.print_linked_list(Solution().rotateRight(ListNode.build_linked_list([1,2,3,4,5]), 2))
    ListNode.print_linked_list(Solution().rotateRight(ListNode.build_linked_list([1,2,3,4,5]), 3))
    ListNode.print_linked_list(Solution().rotateRight(ListNode.build_linked_list([1,2,3,4,5]), 4))
    ListNode.print_linked_list(Solution().rotateRight(ListNode.build_linked_list([1,2,3,4,5]), 5))
    ListNode.print_linked_list(Solution().rotateRight(ListNode.build_linked_list([1,2,3,4,5]), 5))
    ListNode.print_linked_list(Solution().rotateRight(ListNode.build_linked_list([1,2]), 2))
Ejemplo n.º 51
0
class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        from heapq import heapify, heappop, heappush
        h = [(l.val, l) for l in lists if l]
        heapify(h)
        new_head = current = None
        while len(h):
            val, node = heappop(h)
            if node.next:
                heappush(h, (node.next.val, node.next))
            if not new_head:
                current = new_head = node
            else:
                current.next = node
                current = node
                node.next = None
        return new_head


if __name__ == '__main__':
    ListNode.print_linked_list(Solution().mergeKLists([b([1,3,5,7,9]), b([2,4,6,8,10]), b([12,14,15,17,19])]))
    ListNode.print_linked_list(Solution().mergeKLists([b([1,3,5,7,9]), b([2,4,6,8,10]), b([])]))
    ListNode.print_linked_list(Solution().mergeKLists([b([]), b([])]))
    ListNode.print_linked_list(Solution().mergeKLists([]))


Ejemplo n.º 52
0
class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head:
            return head
        n = 0
        p = head
        tail = p
        while p:
            tail = p
            p = p.next
            n += 1
        tail.next = head
        k = k % n
        for i in xrange(n - k):
            tail = tail.next
        new_head = tail.next
        tail.next = None
        return new_head


if __name__ == '__main__':
    f = Solution().rotateRight
    from utils import ListNode
    head = ListNode.make_list([1, 2, 3, 4, 5])
    print f(head, 2)
Ejemplo n.º 53
0
            return head
        elif m == n:
            return head
        c = 1
        prev, current = None, head
        while current:
            if c == m:
                r_head_prev, r_head = prev, current
                prev, current = current, current.next
            elif m < c < n:
                next = current.next
                current.next = prev
                prev, current = current, next
            elif c == n:
                r_tail, r_tail_next = current, current.next
                current.next = prev
                prev, current = current, r_tail_next
            else:
                prev, current = current, current.next
            c += 1
        if r_head_prev:
            r_head_prev.next = r_tail
        r_head.next = r_tail_next

        return head if m > 1 else r_tail

if __name__ == '__main__':
    ListNode.print_linked_list(Solution().reverseBetween(ListNode.build_linked_list([1,2,3,4,5]), 2, 4))
    ListNode.print_linked_list(Solution().reverseBetween(ListNode.build_linked_list([1,2,3,4,5]), 1, 4))
    ListNode.print_linked_list(Solution().reverseBetween(ListNode.build_linked_list([1,2,3,4,5]), 1, 5))
    ListNode.print_linked_list(Solution().reverseBetween(ListNode.build_linked_list([1,2,3,4,5]), 2, 2))
Ejemplo n.º 54
0
        :rtype: ListNode
        """
        if not l1 and not l2:
            return None
        l1_node, l2_node = l1, l2
        l = dummy_new_head = ListNode(1)
        while l1_node and l2_node:
            if l1_node.val <= l2_node.val:
                l.next = ListNode(l1_node.val)
                l1_node = l1_node.next
            else:
                l.next = ListNode(l2_node.val)
                l2_node = l2_node.next
            l = l.next
        l.next = l1_node or l2_node
        return dummy_new_head.next

if __name__ == "__main__":
    ListNode.print_linked_list(ListNode.build_linked_list([1,2,3]))
    #print_ListNode(Solution().mergeTwoLists(None, None))
    #print_ListNode(Solution().mergeTwoLists(None, ListNode(1)))
    #print_ListNode(Solution().mergeTwoLists(build_ListNode([2]), build_ListNode([1])))
    #print_ListNode(Solution().mergeTwoLists(build_ListNode([1]), build_ListNode([2])))
    #print_ListNode(Solution().mergeTwoLists(build_ListNode([1,2,3]), build_ListNode([2, 5,7])))
    ListNode.print_linked_list(
        Solution().mergeTwoLists(
            ListNode.build_linked_list([1, 2, 3]),
            ListNode.build_linked_list([2, 5, 7])
        )
    )
Ejemplo n.º 55
0
        head.next = None
        while current:
            current_next = current.next
            if current.val < sorted_head.val:
                current.next = sorted_head
                sorted_head = current
            else:
                sorted_prev, sorted_current = sorted_head, sorted_head.next
                while sorted_current:
                    if sorted_current.val > current.val:
                        sorted_prev.next = current
                        current.next = sorted_current
                        break
                    sorted_prev, sorted_current = sorted_current, sorted_current.next
                if current.val >= sorted_end.val:
                    current.next = None
                    sorted_end.next = current
                    sorted_end = current

            current = current_next

        return sorted_head

if __name__ == '__main__':
    ListNode.print_linked_list(Solution().insertionSortList(ListNode.build_linked_list([5,1,4,3,2])))
    ListNode.print_linked_list(Solution().insertionSortList(ListNode.build_linked_list([1])))
    ListNode.print_linked_list(Solution().insertionSortList(ListNode.build_linked_list([])))
    ListNode.print_linked_list(Solution().insertionSortList(ListNode.build_linked_list([8,7])))
    ListNode.print_linked_list(Solution().insertionSortList(ListNode.build_linked_list([8,7,1])))
    ListNode.print_linked_list(Solution().insertionSortList(ListNode.build_linked_list([1])))
from utils import TreeNode, ListNode

class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        if head is None:
            return None
        fast, prev, slow = head, None, head
        while fast and fast.next:
            fast = fast.next.next
            prev, slow = slow, slow.next
        root = TreeNode(slow.val)
        if prev:
            prev.next = None
        else:
            return root
        root.left = self.sortedListToBST(head)
        root.right = self.sortedListToBST(slow.next)
        return root


if __name__ == '__main__':
    TreeNode.print_in_level_order(Solution().sortedListToBST(ListNode.build_linked_list([1,2])))
    TreeNode.print_in_level_order(Solution().sortedListToBST(ListNode.build_linked_list([1])))
    TreeNode.print_in_level_order(Solution().sortedListToBST(ListNode.build_linked_list([1,2,3,4,5,6])))
    TreeNode.print_in_level_order(Solution().sortedListToBST(ListNode.build_linked_list([1,2,3,4,5])))
    TreeNode.print_in_level_order(Solution().sortedListToBST(ListNode.build_linked_list([])))