예제 #1
0
def merge(linked_lists):
    merged = []

    # We can collect all nodes in O(n) time, where n is the number of elements
    for node in linked_lists:
        while node:
            merged.append(node.val)
            node = node.next

    # Sorts in O(n log n) time, which results in O(n + n log n), or just O(n log n) time complexity
    sorted_list = sorted(merged)
    # if the return type should be array
    # just return sorted_list

    # if the return type should be Node
    # we need to collect all elements again but this time into a linked list of type Node
    # this step adds O(n) time, but the resulting complexity still remains O (n log n)
    sorted_linked_list = ListNode()
    # so we still can have access to the first node
    head = sorted_linked_list

    for value in sorted_list:
        # Node (value) points to tail, which is None
        sorted_linked_list.next = ListNode(value)
        sorted_linked_list = sorted_linked_list.next

    # return the first node
    return head.next
예제 #2
0
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        if not head:
            return head
        dummy = ListNode(-1)  # 哑节点
        dummy.next = head

        if m > n:
            m, n = n, m

        if n > m:
            p = dummy
            prePm = None
            for _ in range(m):
                prePm = p
                p = p.next

            pM = p
            pNext = p.next
            for _ in range(n - m):
                pPre = p
                p = pNext
                pNext = p.next
                p.next = pPre

            pM.next = pNext
            prePm.next = p
        return dummy.next
예제 #3
0
def run_test_case(t: testlib.unittest.TestCase, tc: Tuple[List[int], int, List[int]]):
    head = ListNode.fromList(tc[0])
    el_to_remove = head
    for _ in range(tc[1]):
        el_to_remove = el_to_remove.next
    Solution().deleteNode(el_to_remove)
    t.assertEqual(repr(head), repr(ListNode.fromList(tc[2])))
예제 #4
0
 def push(self, value):
     newnode = ListNode(value, self._top)
     if self._top is None:
         self._top = newnode
     else:
         newnode._next = self._top
         self._top = newnode
예제 #5
0
 def reverseBetween(self, head, m, n):
     """
     :type head: ListNode
     :type m: int
     :type n: int
     :rtype: ListNode
     """
     if not head:
         return head
     dummy = ListNode(-1)
     dummy.next = head
     left, cur = dummy, head
     k = n - m + 1
     while m > 1:
         left = cur
         cur = cur.next
         m -= 1
     # reserve k times
     start = cur
     prev = None
     while k:
         tmp = cur.next
         cur.next = prev
         prev = cur
         cur = tmp
         k -= 1
     # connect together
     left.next = prev
     start.next = cur
     return dummy.next
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        if not head or k == 1:
            return head

        dummy = ListNode(-1)
        dummy.next = head
        l, r = dummy, dummy
        step = 0
        while r:
            r = r.next
            if r:
                step += 1
            if step == k:
                step = 0
                # 翻转 l 和r 之间的所有节点
                tmp = l.next
                prev = r.next
                while True:
                    next = tmp.next
                    tmp.next = prev
                    prev = tmp
                    if tmp == r:
                        break
                    tmp = next
                tmp = l.next
                l.next = r
                l, r = tmp, tmp

        return dummy.next
예제 #7
0
 def test_delete_duplicates_2(self):
     node5 = ListNode(3, None)
     node4 = ListNode(3, node5)
     node3 = ListNode(2, node4)
     node2 = ListNode(1, node3)
     node1 = ListNode(1, node2)
     test = self.leet83.delete_duplicates(node1)
     self.assertEqual(test.next.next.val, 3)
예제 #8
0
def array_to_listnode(array):
    if len(array) > 0:
        head = ListNode(array[0])
        temp = head
        for e in array[1:]:
            node = ListNode(e)
            temp.next = node
            temp = temp.next
        return head
예제 #9
0
 def test_has_value(self):
     node1 = ListNode(15)
     node2 = ListNode(8.2)
     node3 = ListNode("Berlin")
     self.assertTrue(node1.has_value(15))
     self.assertTrue(node2.has_value(8.2))
     self.assertTrue(node3.has_value("Berlin"))
 def mergeKLists(self, lists: List[ListNode]) -> ListNode:
     nodes = []
     for list in lists:
         while list:
             nodes.append(list.val)
             list = list.next
     head = point = ListNode(-1)
     for x in sorted(nodes):
         point.next = ListNode(x)
         point = point.next
     return head
예제 #11
0
    def _addToTail(self, node: ListNode):
        """Add node to tail."""
        if not self.head:
            self.head = node
            return

        parent = self.head
        while parent.nextNode:
            parent = parent.nextNode

        node.setNextNode(parent.getNextNode())
        parent.setNextNode(node)
예제 #12
0
def string_to_list_node(string):
    # Generate list from the input
    numbers = string_to_integer_list(string)

    # Now convert that list into linked list
    dummy_root = ListNode(0)
    ptr = dummy_root
    for number in numbers:
        ptr.next = ListNode(number)
        ptr = ptr.next

    ptr = dummy_root.next
    return ptr
예제 #13
0
    def addNode(self, data: int, addToTail: bool = False):
        """Add new node to the SinglyLinked List.

        :param int data: data to be stored in linked list
        :param bool addToTail: Indicate whether data to be added at tail
        """
        if self.findNode(data):
            raise Exception("Duplicate Data")
        node = ListNode(data)
        if addToTail:
            return self._addToTail(node)
        node.setNextNode(self.head)
        self.head = node
예제 #14
0
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        result = []
        head = current = ListNode(0)

        for l in lists:
            while l:
                result.append(l.val)
                l = l.next

        for v in sorted(result):
            current.next = ListNode(v)
            current = current.next

        return head.next
예제 #15
0
    def add_list_item(self, item):

        if (not isinstance(item, ListNode)):
            item = ListNode(item)

        if (self.head is None):
            self.head = item
            item.next = None
            item.prev = None
            self.tail = item
        else:
            self.tail.next = item
            item.prev = self.tail
            self.tail = item
예제 #16
0
파일: Test.py 프로젝트: manjory/start_test
def main():
    # print("Starting")
    # head1 = ListNode(1)
    # head1.next = ListNode(3)
    # head1.next.next = ListNode(16)
    # # head1.next.next.next = ListNode(5)
    # tmp = head1
    # head2 = ListNode(1)
    # head2.next = ListNode(1)
    # head2.next.next=ListNode(9)
    sol=Solution()
    # head3 = sol.mergeSortedLists(head1,head2)
    # tmp = head3
    sample_del=ListNode(1)
    sample_del.next=ListNode(1)
    sample_del.next.next=ListNode(2)
    sample_del.next.next.next=ListNode(3)
    sample_del.next.next.next.next=ListNode(3)
    sample_del.next.next.next.next.next=ListNode(4)
    head4=sol.deleteDuplicates(sample_del)
    tmp_del=head4
    while tmp_del:
        print(tmp_del.val)
        tmp_del=tmp_del.next
    print ("\n\n")
예제 #17
0
 def deleteDuplicates(self, list_node):
     if not list_node:
         return list_node
     head = ListNode(None)
     head.next = list_node
     previous_node = head
     current_node = head.next
     while current_node:
         next_node = current_node.next
         if previous_node.val == current_node.val:
             self.unlink_list_node(previous_node, current_node)
         else:
             previous_node = current_node
         current_node = next_node
     return head.next
예제 #18
0
 def get_detect_cycle_result(self, list_node_string, position):
     linked_list = string_to_list_node(list_node_string)
     linked_list = self.make_linked_list_cycle(linked_list, position)
     list_node = self.solution.detectCycle(linked_list)
     if list_node:
         list_node = ListNode(list_node.val)
     return list_node_to_string(list_node)
예제 #19
0
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        if not lists:
            return None

        # 删掉空节点
        lists = [a for a in lists if a]
        if not lists:
            return None

        head = ListNode(-1)
        tail = head
        priority_queue = PriorityQueue()
        for index, node in enumerate(lists):
            priority_queue.put((node.val, index, node))

        while not priority_queue.empty():
            val, index, node = priority_queue.get()

            tail.next = node
            tail = node
            if node.next:
                node = node.next
                priority_queue.put((node.val, index, node))

        return head.next
예제 #20
0
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
    if not l2 or not l1:
        return l1 or l2
    if l1.val > l2.val:
        l1, l2 = l2, l1
    head = l1
    while l1.next and l2:
        if l2.val < l1.next.val:
            next1, next2 = l1.next, l2.next
            l1.next, l2.next = l2, next1
            l1, l2 = l2, next2
        else:
            l1 = l1.next
    if l2:
        l1.next = l2
    return head
예제 #21
0
        def merge(head1: ListNode, head2: ListNode) -> ListNode:
            """归并排序

            Args:
                head1 (ListNode): 列表1头结点
                head2 (ListNode): 列表2头结点

            Returns:
                ListNode: 合并后的列表
            """
            dummy = ListNode(-1)
            tmp, tmp1, tmp2 = dummy, head1, head2
            while tmp1 and tmp2:
                if tmp1.val <= tmp2.val:
                    tmp.next = tmp1
                    tmp1 = tmp1.next
                else:
                    tmp.next = tmp2
                    tmp2 = tmp2.next
                tmp = tmp.next
            if tmp1:
                tmp.next = tmp1
            elif tmp2:
                tmp.next = tmp2
            return dummy.next
 def put_even_numbers_before_odd_numbers(self, head):
     dummy_even = ListNode(-1)
     cur = dummy_even
     dummy_odd = ListNode(-1)
     cur_odd = dummy_odd
     while head:
         if head.val % 2 == 0:
             cur.next = head
             cur = cur.next
         else:
             cur_odd.next = head
             cur_odd = cur_odd.next
         head = head.next
     # critical: cut ending
     cur.next, cur_odd.next = None, None
     cur.next = dummy_odd.next
     return dummy_even.next
예제 #23
0
 def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
     preHead = ListNode(0)
     preHead.next = head
     cur = preHead
     for i in range(0, m - 1):
         cur = cur.next
     start = cur
     cur = cur.next
     end = cur
     cur = cur.next
     for i in range(m, n):
         temp = start.next
         start.next = cur
         cur = cur.next
         start.next.next = temp
     end.next = cur
     return preHead.next
예제 #24
0
 def swapPairs(self, linked_list):
     if not linked_list:
         return linked_list
     head = ListNode(None)
     head.next = linked_list
     processed_node = head
     while processed_node.next:
         first_node = processed_node.next
         second_node = first_node.next
         if not second_node:
             return head.next
         second_node_next = second_node.next
         processed_node.next = second_node
         second_node.next = first_node
         first_node.next = second_node_next
         processed_node = first_node
     return head.next
예제 #25
0
 def removeElements(self, head: ListNode, val: int) -> ListNode:
     """
     O(n) time
     O(n) space => TBD O(1) space
     """
     dummyHead = ListNode(0)
     p, q = head, dummyHead
     while p is not None:
         v = p.val
         if v == val:
             p = p.next
             continue  # skip it
         # Non-skip case
         q.next = ListNode(v)
         q = q.next
         p = p.next
     return dummyHead.next
예제 #26
0
 def reverseList(node: ListNode) -> ListNode:
     h, prev = node, None
     while node:
         h = node
         next = node.next
         node.next = prev
         prev = h
         node = next
     return h
예제 #27
0
    def addTwoNumbers(self, l1, l2):
        output = ListNode(0)
        carry = 0
        dummy = output
        while l1 is not None or l2 is not None:
            while l1 is not None:
                carry += l1.val
                l1 = l1.next
            while l2 is not None:
                carry += l2.val
                l2 = l2.next

            dummy.next = ListNode(carry % 10)
            carry = carry / 10

            dummy = dummy.next

        return output.next
예제 #28
0
 def make_linked_list_cycle(self, linked_list, position):
     if not linked_list or position == -1:
         return linked_list
     head = ListNode(None)
     head.next = linked_list
     current_node = head.next
     target_node = None
     last_node = None
     index = 0
     while current_node:
         if index == position:
             target_node = current_node
         last_node = current_node
         current_node = current_node.next
         index += 1
     if target_node:
         last_node.next = target_node
     return head.next
예제 #29
0
 def removeElements(self, head: ListNode, val: int) -> ListNode:
     dummy = ListNode(-1, head)
     p = dummy
     while p.next:
         if p.next.val == val:
             p.next = p.next.next  # 删除节点
         else:
             p = p.next
     return dummy.next
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        
        dummyNode = ListNode(-1)
        dummyNode.next = head
        first, second = dummyNode, dummyNode.next.next  # second 和 first 间隔一个节点

        while second:
            # 交换节点
            tmp = first.next
            first.next = second
            tmp.next = second.next
            second.next = tmp
            second = tmp.next.next if tmp.next else None
            first = tmp

        return dummyNode.next