예제 #1
0
 def mergeInBetween(self, list1, a, b, list2):
     """
     :type list1: ListNode
     :type a: int
     :type b: int
     :type list2: ListNode
     :rtype: ListNode
     """
     dummy = ListNode(-1)
     dummy.next = list1
     cur = dummy
     cnt, a, b = 0, a + 1, b + 2
     tail1, head1 = None, None
     while cur:
         pre = cur
         cur = cur.next
         cnt += 1
         if cnt == a: tail1 = pre
         if cnt == b:
             head1 = cur
             pre.next = None
             break
     cur = list2
     while cur.next:
         cur = cur.next
     tail1.next = list2
     cur.next = head1
     return dummy.next
예제 #2
0
    def rotateList(self, head, k):
        if head == None or head.next == None:
            return head

        fake_node = ListNode(0)
        fake_node.next = head
        fast = fake_node
        slow = fake_node

        # calculate the length
        l = 0
        while fast.next != None:
            fast = fast.next
            l += 1

        # we need to move the list after (l-k%l)th node
        node_pos = l - k % l
        while node_pos > 0:
            slow = slow.next
            node_pos -= 1

        fast.next = fake_node.next
        fake_node.next = slow.next
        slow.next = None

        return fake_node.next
예제 #3
0
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        """
        Running time: O(nk)
        Space complexity: O(k)
        """
        merged = ListNode('*')
        merged_head = merged
        first_nodes_vals = list()
        for i, node in enumerate(lists):
            if node is not None:
                bisect.insort(first_nodes_vals, (node.val, i))

        while first_nodes_vals:
            # find the node with the next min value
            _, idx = first_nodes_vals.pop(0)
            # add it to the merged seq
            merged.next = lists[idx]
            # update merged and lists[idx]
            new_head_subseq = lists[idx].next
            merged = merged.next
            merged.next = None
            lists[idx] = new_head_subseq
            # add new value to first_nodes_vals if applicable
            if lists[idx] is not None:
                bisect.insort(first_nodes_vals, (lists[idx].val, idx))
        return merged_head.next
예제 #4
0
 def swapNodes(self, head, v1, v2):
     # write your code here
     dummy = ListNode(-1)
     dummy.next = head
     pre, cur = dummy, head
     n1, n2 = None, None
     n1p, n2p = None, None
     n1x, n2x = None, None
     while cur:
         if cur.val == v1:
             n1, n1p, n1x = cur, pre, cur.next
         if cur.val == v2:
             n2, n2p, n2x = cur, pre, cur.next
         pre = cur
         cur = cur.next
     if n1 and n2:
         if n1.next == n2:
             n1p.next = n2
             n2.next = n1
             n1.next = n2x
         elif n2.next == n1:
             n2p.next = n1
             n1.next = n2
             n2.next = n1x
         else:
             n1p.next = n2
             n2.next = n1x
             n2p.next = n1
             n1.next = n2x
     return dummy.next
예제 #5
0
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None or head.next is None:
            return head

        tempNode = ListNode(0)
        tempNode.next = head

        cur = head
        prev = tempNode
        while cur.next is not None:
            if cur.val != cur.next.val:
                remove = False
                if prev.next == cur:
                    prev = prev.next
                else:
                    prev.next = cur.next
            else:
                remove = True
            cur = cur.next

        if remove:
            prev.next = cur.next
        return tempNode.next
예제 #6
0
def addTwoNumbers(l1, l2):
    carry = 0
    ptr_l1 = l1
    ptr_l2 = l2
    dummy_root = ListNode(0)
    ptr_res = dummy_root
    while ptr_l1 and ptr_l2:
        s = ptr_l1.val + ptr_l2.val + carry
        carry = int(s / 10)
        # print(s % 10, carry)
        ptr_res.next = ListNode(s % 10)
        ptr_res = ptr_res.next
        ptr_l1 = ptr_l1.next
        ptr_l2 = ptr_l2.next
    while ptr_l1:
        s = carry + (ptr_l1.val if ptr_l1 else 0)
        carry = int(s / 10)
        ptr_res.next = ListNode(s % 10)
        ptr_res = ptr_res.next
        ptr_l1 = ptr_l1.next
    while ptr_l2:
        s = carry + (ptr_l2.val if ptr_l2 else 0)
        carry = int(s / 10)
        ptr_res.next = ListNode(s % 10)
        ptr_res = ptr_res.next
        ptr_l2 = ptr_l2.next

    if carry:
        ptr_res.next = ListNode(carry)

    return dummy_root.next
예제 #7
0
def list_pivoting(L, p):
    '''Partition L so nodes with value less than p comes before p, and nodes with
	value greater than p comes after p
	'''
    # create 3 linked list to store the three partitions
    # constant space since reusing existing nodes
    less_head = less_iter = ListNode()
    equal_head = equal_iter = ListNode()
    greater_head = greater_iter = ListNode()
    # iterate through list and append node to appropriate lists
    while L:
        if L.data < p:
            less_iter.next = L
            less_iter = less_iter.next
        elif L.data > p:
            greater_iter.next = L
            greater_iter = greater_iter.next
        else:  # equal to p
            equal_iter.next = L
            equal_iter = equal_iter.next
        # process next node
        L = L.next
    # join the three partitions
    greater_iter.next = None
    equal_iter.next = greater_head.next
    less_iter.next = equal_head.next
    return less_head.next
def removeNthFromEnd(head, n):
    start = ListNode(0)
    slow, fast = start, start
    start.next = head
    for i in range(0, n + 1):
        fast = fast.next
    while fast:
        slow = slow.next
        fast = fast.next
    slow.next = slow.next.next
    return start.next
 def mergeKLists(self, lists):
     items = []
     for node in lists:
         while node:
             items.append(node.val)
             node = node.next
     dummy = cur = ListNode(None)
     for i in sorted(items):
         cur.next = ListNode(i)
         cur = cur.next
     return dummy.next
예제 #10
0
def swapPairs2(head):
    node = ListNode(0)
    node.next = head
    prev, curr = node, head
    while curr and curr.next:
        temp = curr.next.next
        curr.next.next = prev.next
        prev.next = curr.next
        curr.next = temp
        prev = curr
        curr = prev.next
    return node.next
예제 #11
0
 def swapPairs(self, head):
     """
     :type head: ListNode
     :rtype: ListNode
     """
     dummy = ListNode(None)
     dummy.next = head
     cur = dummy
     while cur.next and cur.next.next:
         a, b = cur.next, cur.next.next
         cur.next, b.next, a.next = b, a, b.next  # swap
         cur = cur.next.next  # link is restored after swap
     return dummy.next
예제 #12
0
 def removeNthFromEnd2(self, head, n):
     dummy = ListNode(0)
     dummy.next = head
     first = dummy
     second = dummy
     for _ in range(n + 1):
         if first == None:
             return head
         first = first.next
     while (first != None):
         first = first.next
         second = second.next
     second.next = second.next.next
     return dummy.next
예제 #13
0
 def partition(self, A, B):
     dummy_left = cur_left = ListNode(None)
     dummy_right = cur_right = ListNode(None)
     while A:
         if A.val < B:
             cur_left.next = A
             cur_left = cur_left.next
         else:
             cur_right.next = A
             cur_right = cur_right.next
         A = A.next
     cur_right.next = None # end of right might not be empty!
     cur_left.next = dummy_right.next
     return dummy_left.next
def Merger(a: ListNode, b: ListNode):
    if a is None:
        return b
    elif b is None:
        return a

    if a.val < b.val:
        a.next = Merger(a.next, b)
        result = a
    else:
        b.next = Merger(a, b.next)
        result = b

    return result
예제 #15
0
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """

        tempNodeL = ListNode(0)
        tempNodeH = ListNode(0)

        headL = tempNodeL
        headH = tempNodeH

        while head:
            if head.val < x:
                tempNodeL.next = head
                tempNodeL = tempNodeL.next
            else:
                tempNodeH.next = head
                tempNodeH = tempNodeH.next

            head = head.next

        tempNodeH.next = None
        tempNodeL.next = headH.next

        return headL.next
예제 #16
0
def insertionSortList(A):
    if A==None or A.next == None:
        return A
    current = res = ListNode(A.val)
    A = A.next
    while A:
        if current.val>A.val:
            head = res
            #it means node will come before head
            if head.val>A.val:
                temp = ListNode(A.val)
                temp.next = head
                res = temp
                A=A.next
            else:
                while head and head.next and head.next.val<A.val:
                    head = head.next
                temp = ListNode(A.val)
                temp.next = head.next
                head.next = temp
                A=A.next
        else:
            current.next = ListNode(A.val)
            current = current.next
            A = A.next
    return res
예제 #17
0
 def addTwoNumbers(self, A, B):
     dummy = node = ListNode(None)
     carry = 0
     while A or B or carry:
         a_val = A.val if A else 0
         b_val = B.val if B else 0
         total = a_val + b_val + carry
         carry, cur_val = divmod(total, 10)
         node.next = ListNode(cur_val)
         node = node.next
         if A:
             A = A.next
         if B:
             B = B.next
     return dummy.next
예제 #18
0
def addTwoNumbers2(l1, l2):
    dummy_root = ListNode(0)
    ptr = dummy_root
    carry = 0
    while l1 or l2 or carry:
        l1_val = l1.val if l1 else 0
        l2_val = l2.val if l2 else 0
        s = l1_val + l2_val + carry
        ptr.next = ListNode(s % 10)
        carry = s // 10
        if l1: l1 = l1.next
        if l2: l2 = l2.next
        ptr = ptr.next
    # print(listNodeToList(dummy_root.next))
    return dummy_root.next
예제 #19
0
 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
     p1, p2 = l1, l2
     current = result = ListNode(0)
     previous = None
     while p1 or p2 :
         m_sum = (p1.val if p1 else 0) + (p2.val if p2 else 0) + current.val
         current.val = m_sum % 10
         current.next = ListNode(int(m_sum / 10))
         previous = current
         current = current.next
         p1 = p1.next if p1 else None
         p2 = p2.next if p2 else None
     if previous.next.val == 0:
         previous.next = None
     return result
예제 #20
0
def partition(head, x):
    curr = head
    head = tempHead = ListNode(0)
    pivot = tempPivot = ListNode(x)
    while curr:
        if curr.val < x:
            tempHead.next = curr
            tempHead = tempHead.next
        else:
            tempPivot.next = curr
            tempPivot = tempPivot.next
        curr = curr.next
    tempHead.next = pivot.next
    tempPivot.next = None
    return head.next
예제 #21
0
def addTwoNumbers2(l1, l2):
    head = ListNode(0)
    carry, temp = 0, head
    while l1 or l2 or carry:
        if l1:
            temp.val += l1.val
            l1 = l1.next
        if l2:
            temp.val += l2.val
            l2 = l2.next
        carry = temp.val / 10
        temp.val %= 10
        if l1 or l2 or carry:
            temp.next = ListNode(carry)
            temp = temp.next
    return head
예제 #22
0
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        dummy = ListNode(0)
        dummy.next = head
        slow = dummy
        fast = head

        for _ in range(n):
            fast = fast.next

        while fast:
            slow = slow.next
            fast = fast.next

        slow.next = slow.next.next

        return dummy.next
예제 #23
0
 def mergeTwoLists(self, l1, l2):
     """
     :type l1: ListNode
     :type l2: ListNode
     :rtype: ListNode
     """
     # If either list is empty return the other list
     if not l1:
         return l2
     if not l2:
         return l1
     # Use newList for return and curNode for processing each node in the list
     newList = curNode = ListNode(0)
     while l1 and l2:
         if l1.val < l2.val:
             curNode.next = l1
             l1 = l1.next
         else:
             curNode.next = l2
             l2 = l2.next
         curNode = curNode.next
     # Append the list that still has data to the end
     # All the values will be the largest
     if l1:
         curNode.next = l1
     else:
         curNode.next = l2
     # The or operator in assignment takes the first value that evaluates to True
     # and returns it. It's equivalent to the above if/else in this case
     # curNode.next = l1 or l2
     return newList.next
예제 #24
0
 def solve_for_lists(lst: List[List[int]]) -> 'ListNode':
     lst = [ListNode.to_linkedlist(l) for l in lst]
     ans = Solution().mergeKLists(lst)
     if ans is None:
         return []
     else:
         return ans.to_list()
예제 #25
0
def mergeKLists1(lists):
    if not lists:
        return None
    elif len(lists) == 1:
        return lists[0]
    elif len(lists) == 2:
        head = temp = ListNode(0)
        l1, l2 = lists[0], lists[1]
        while l1 and l2:
            if l1.val < l2.val:
                temp.next = l1
                l1 = l1.next
            else:
                temp.next = l2
                l2 = l2.next
            temp = temp.next
        if l1:
            temp.next = l1
        if l2:
            temp.next = l2
        return head.next
    else:
        length = len(lists) / 2
        return mergeKLists1(
            [mergeKLists1(lists[:length]),
             mergeKLists1(lists[length:])])
 def removeDuplicates(self, head):
     m = defaultdict(int)
     dummy = ListNode(-1)
     dummy.next = head
     cur = head
     while cur:
         m[cur.val] += 1
         cur = cur.next
     pre = dummy
     cur = head
     while cur:
         if m[cur.val] == 1:
             pre.next = cur
             pre = cur
         cur = cur.next
     pre.next = None
     return dummy.next
예제 #27
0
 def remove_node(self, head: ListNode) -> ListNode:
     """
     Runtime and space complexity: O(1)
     """
     node = head.next
     head.next = head.next.next
     node.next = None
     return node
예제 #28
0
 def make_tree(arr):
     head = ListNode('*')
     head2 = head
     mapping = []
     for val, _ in arr:
         head2.next = ListNode(val)
         head2 = head2.next
         mapping.append(head2)
     head = head.next
     head2 = head
     for _, random in arr:
         if random is None:
             head2.random = None
         else:
             head2.random = mapping[random]
         head2 = head2.next
     return head
예제 #29
0
def list_partition(head):
    pivot = median3(head)
    s_head = s_ptr = ListNode(float("-inf"))
    l_head = l_ptr = ListNode(float("-inf"))
    p_head = p_ptr = ListNode(float("-inf"))
    while head:
        if head.val < pivot:
            s_ptr.next = head
            s_ptr = s_ptr.next
        elif head.val > pivot:
            l_ptr.next = head
            l_ptr = l_ptr.next
        else:
            p_ptr.next = head
            p_ptr = p_ptr.next
        head = head.next
    s_ptr.next, l_ptr.next, p_ptr.next = None, None, None
    return s_head.next, l_head.next, p_head.next, p_ptr
예제 #30
0
 def reverseList_n(self, head: ListNode, n: int) -> ListNode:
     global successor
     if (n == 1):
         successor = head.next
         return head
     last = self.reverseList_n(head.next, n - 1)
     head.next.next = head
     head.next = successor
     return last
예제 #31
0
    def addTwoNumbers(self, A, B):
        #pdb.set_trace()
        A = self.reverseLinkedList(A)
        B = self.reverseLinkedList(B)
        if A is None:
            return B
        elif B is None:
            return A
        sum = A.val + B.val
        carry = sum / 10
        C = ListNode(sum % 10)
        returnHead = C
        A = A.next
        B = B.next
        
        while A is not None and B is not None:
            sum = A.val + B.val + carry
            carry = sum / 10
            C.next = ListNode(sum % 10)
            C = C.next
            A = A.next
            B = B.next
        
        while A is not None:
            sum = A.val + carry
            carry = sum / 10
            C.next = ListNode(sum % 10)
            C = C.next
            A = A.next

        while B is not None:
            sum = B.val + carry
            carry = sum / 10
            C.next = ListNode(sum % 10)
            C = C.next
            B = B.next
        
        if carry != 0:
            C.next = ListNode(carry)

        return returnHead
예제 #32
0
from MergeSortedList import Solution
from LinkedList import ListNode

head01 = ListNode(1)
head02 = ListNode(2)

p01 = ListNode(3)
p02 = ListNode(5)
p03 = ListNode(7)

q01 = ListNode(6)
q02 = ListNode(8)
q03 = ListNode(9)

head01.next = p01
p01.next = p02
p02.next = p03

head02.next = q01
q01.next = q02
q02.next =q03

test = Solution()

testHead = test.mergeTwoLists(head01, head02)

while testHead:
	print testHead.val
	testHead = testHead.next
from LinkedListCycle import Solution
from LinkedList import ListNode

node01 = ListNode(1)
node02 = ListNode(2)
node03 = ListNode(3)
node04 = ListNode(4)
node05 = ListNode(5)

node01.next = node02
#node02.next = node03
node03.next = node04
node04.next = node05
node05.next = node04

test = Solution()

result = test.detectCycle(node01)
print result.val if result else None
예제 #34
0
 def push(self, item):
     node = ListNode(item)
     if not self.isEmpty():
         node.next = self._head
     self._head = node
     self._count += 1