Exemplo n.º 1
0
def add(x, y):
	start = ListNode(-1)
	res= start
	values = [0]
	x1, x2= x, y
	m, n = 0, 0
	while x1:
		x1 = x1.next
		m += 1
	while x2:
		x2 = x2.next
		n += 1
	# make sure x is the longer
	if n > m:
		x, y, m ,n = y, x, n, m

	for i in range(m-n):
		values.append(x.val)
		x = x.next

	for _ in range(n):
		values.append(x.val + y.val)
		x, y = x.next, y.next

	for idx in range(len(values)-1, 0, -1):
		values[idx-1]= values[idx -1] + values[idx]/10
		values[idx] = values[idx] % 10
	for k in range(len(values)):
		start.next= ListNode(values[k])
		start = start.next
	if res.next.val == 0:
		return res.next.next
	return res.next
Exemplo n.º 2
0
def partition(head, x):
    """
	:type head: ListNode
	:type x: int
	:rtype: ListNode
	"""
    if not head:
        return head
    dummy = ListNode(0)
    dummy.next = head
    curr = last = mark = dummy
    while curr.next:
        if curr.next.val >= x:
            last = curr
            mark = curr.next
            break
        curr = curr.next
    stack = []
    while mark.next:
        if mark.next.val < x:
            stack.append(mark.next.val)
            mark.next = mark.next.next
        else:
            mark = mark.next
    while stack:
        val = stack.pop(0)
        temp = last.next
        last.next = ListNode(val)
        last.next.next = temp
        last = last.next
    return dummy.next
Exemplo n.º 3
0
def deleteDuplicates2(head):
    if head == None or head.next == None:
        return head
    p = head
    cur = p.val
    dup = False
    lastHead = None
    lastDis = None
    while p.next != None:
        if p.next.val == cur:
            dup = True
            p = p.next
        elif not dup:
            if lastDis == None:
                lastHead = ListNode.ListNode(p.val)
                lastDis = lastHead
            else:
                lastDis.next = ListNode.ListNode(p.val)
                lastDis = lastDis.next
            p = p.next
            cur = p.val
            dup = False
        else:
            p = p.next
            cur = p.val
            dup = False

    if not dup:
        if lastDis == None:
            lastHead = ListNode.ListNode(p.val)
            lastDis = lastHead
        else:
            lastDis.next = ListNode.ListNode(p.val)
    return lastHead
Exemplo n.º 4
0
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        stk1, stk2 = [], []
        while l1:
            stk1.append(l1.val)
            l1 = l1.next
        while l2:
            stk2.append(l2.val)
            l2 = l2.next

        prev, head = None, None
        sum = 0
        while stk1 or stk2:
            sum /= 10
            if stk1:
                sum += stk1.pop()
            if stk2:
                sum += stk2.pop()

            head = ListNode(sum % 10)
            head.next = prev
            prev = head

        if sum >= 10:
            head = ListNode(sum / 10)
            head.next = prev

        return head
Exemplo n.º 5
0
    def addTwoNumbers(self, l1, l2):
        numbers = []
        for l in (l1, l2):
            tens = 1
            no = 0
            no = no + (l.val * tens)
            tens = tens * 10
            while (l.next_node != None):
                no = no + l.next_node.val * tens
                tens = tens * 10
                l = l.next_node
            numbers.append(no)

        l_sum = numbers[0] + numbers[1]
        first_val = l_sum % 10
        l_sum = l_sum / 10
        l3 = ListNode.ListNode(first_val)
        head = l3
        while (l_sum > 0):
            val = l_sum % 10
            l_sum = l_sum / 10
            l_node = ListNode.ListNode(val)
            l3.next_node = l_node
            l3 = l3.next_node

        return head
Exemplo n.º 6
0
	def isPalindrome(head):
		if head == None:
                        return True
                temp_node = ListNode(head.val)
                orig_head = temp_node
                node  = head
                while node.next != None:
                        node = node.next
                        new_node = ListNode(node.val)
                        temp_node.next = new_node
                        temp_node = new_node 
                        
                next_node = None
                prev_node = None
                curr_node = head
                while curr_node != None:
                        next_node = curr_node.next
                        curr_node.next = prev_node
                        prev_node = curr_node
                        curr_node = next_node
                        
                head = prev_node
                isPalindrome = True
                
                while head.next != None:
                        if head.val != orig_head.val:
                                isPalindrome = False
                                break
                        else:   
                                head = head.next
                                orig_head = orig_head.next
                                
                return isPalindrome
Exemplo n.º 7
0
 def addTwoNumbersHelper(self, n1 , n2, has_carry=0):
     """
     Recursive Helper used to add two ListNode of Numbers.
     Note: Subtract is used over Division since Subtraction has a faster runtime than subtraction
           See https://stackoverflow.com/questions/1396564/why-is-subtraction-faster-than-addition-in-python
           This is also useful because the carry will NEVER be more than one
     :param n1: First set of Numbers to add
     :param n2: Second set of Numbers to add
     :param has_carry: Boolean value if numbers are carried
     :return: Resulting ListNode
     """
     if n1 is None:
         if n2 is None:
             if has_carry:
                 return ListNode(1)
             else:
                 return None
         n1 = ListNode(0)
     elif n2 is None:
         n2 = ListNode(0)
     total = n1.val + n2.val + has_carry
     if total > 9:
         has_carry = 1
         total -= 10
     else:
         has_carry = 0
     currentNode = ListNode(total)
     currentNode.next = self.addTwoNumbersHelper(n1.next, n2.next, has_carry)
     return currentNode
Exemplo n.º 8
0
def addTwoNumbers(l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    dummy = ListNode(-1)
    output = dummy
    if not l1 and not l2:
        return
    if not l1:
        return l2
    if not l2:
        return l1
    carry = 0
    while l1 or l2:
        a = l1.val if l1 else 0
        b = l2.val if l2 else 0
        add = a + b + carry
        if add > 9:
            add = add % 10
            carry = (a + b + carry) // 10
            dummy.next = ListNode(add)
        else:
            dummy.next = ListNode(add)
            carry = 0
        dummy = dummy.next
        if l1:
            l1 = l1.next
        if l2:
            l2 = l2.next
    print(carry)
    if carry > 0:
        dummy.next = ListNode(carry)
    return output.next
Exemplo n.º 9
0
def reorder(head):
    if not head: return None
    it = curr = head
    # construct a reverse list
    p_head = p = ListNode(it.val)
    length = 1
    while it.next:
        it = it.next
        length += 1
        p.next = ListNode(it.val)
        p = p.next
    tail = reverse(p_head)

    # construct the reordered list
    count = 0
    while count < length:
        store = tail.next
        temp = curr.next
        curr.next = tail
        count += 1
        if count == length:
            curr.next = None
            break
        tail.next = temp
        count += 1
        if count == length:
            curr.next.next = None
            break
        curr = temp
        tail = store
        # show(head)
    return head
    def revHelp(self, head):
        if head.next == None:
            l2 = ListNode(head.val)
            return (l2, l2)

        rev, last = self.revHelp(head.next)
        last.next = ListNode(head.val)
        return (rev, last.next)
 def enqueue(self, item):
     if self.front == None:
         self.front = ListNode(item)
         self.rear = self.front
     else:
         temp = ListNode(item)
         current = self.rear
         self.rear = temp
         current.set_link(temp)
Exemplo n.º 12
0
 def __init__(self):
     self.front = ListNode()
     self.back = ListNode()
     self.front.setNext(self.back)
     self.front.setPrev(None)
     self.back.setPrev(self.front)
     self.back.setNext(None)
     self.current = self.front
     return None
Exemplo n.º 13
0
 def create_LinkedList(arr=None):
     if len(arr) == 0:
         return None
     else:
         head = ListNode(int(arr[0]))
         temp = head
         for i in arr[1:]:
             temp.next = ListNode(int(i))
             temp = temp.next
         return head
Exemplo n.º 14
0
def main():
    vec = [2, 3, 9, 5, 1, 7]
    head = ListNode.ListNode(0)
    head.creatFromList(vec)

    vec2 = [0] * 500
    head2 = ListNode.ListNode(0)
    head2.creatFromList(vec2)

    s = Solution()
    s.test(head.next, True)
    s.test(head2.next, False)
    def insert_front(self, item):

        # if node is empty adds item
        if self.head == None:
            self.head = ListNode(item)

        #adds item when the list isnt empty
        else:
            temp = ListNode(item)
            temp.set_link(self.head)
            self.head = temp
            temp = None
Exemplo n.º 16
0
    def createListNodes(self, sortedLists):
        result = []
        for l in sortedLists:
            dummyHead = ListNode.ListNode(None)
            current = dummyHead
            for i in range(len(l)):
                node = ListNode.ListNode(l[i])
                current.next = node
                current = node

            result.append(dummyHead.next)
        return result
Exemplo n.º 17
0
    def create_linked_list(node_value_list):
        """Construct linked list from give list

        :param node_value_list: Python list with node values
        :return: Head node of the constructed list
        """
        temp = head = ListNode.ListNode(node_value_list[0])
        for v in node_value_list:
            node = ListNode.ListNode(v)
            temp.next = node
            temp = temp.next
        return head
Exemplo n.º 18
0
        def add(n0, n1):
            carry = 0
            head = curr = ListNode(-1)
            while n0 != None or n1 != None:
                carry, out = divmod(get(n0) + get(n1) + carry, 10)
                curr.next = ListNode(out)
                curr = curr.next
                if (n0 != None): n0 = n0.next
                if (n1 != None): n1 = n1.next

            if (carry != 0): curr.next = ListNode(carry)

            return head.next
def main():
    array = [1, 2, 5, 6, 7, 9]
    head1 = ListNode.ListNode(0)
    head1.creatFromList(array)

    array2 = list(random.sample(range(10000), 10000))
    head2 = ListNode.ListNode(0)
    head2.creatFromList(array2)

    s = Solution()
    s.test(head1, 2)
    s.test(head1, 10)
    s.test(head2, 100)
    s.test(head2, 300)
Exemplo n.º 20
0
 def __init__(self, x):
     self.x = x
     print "Created Object"
     l11 = ListNode.ListNode(1)
     l12 = ListNode.ListNode(2)
     l11.next_node = l12
     l21 = ListNode.ListNode(5)
     l22 = ListNode.ListNode(6)
     l21.next_node = l22
     l3 = self.addTwoNumbers(l11, l21)
     print 'l3 val in init', l3.val
     while (l3.next_node != None):
         print 'l3 val in init', l3.next_node.val
         l3 = l3.next_node
    def insert_end(self, item):

        #if the list is empty it add the item to the list
        if self.head == None:
            self.head = ListNode(item)

    # adds item to the list when the list is not empty
        else:
            current = self.head
            temp = ListNode(item)

            while current.get_link() != None:
                current = current.get_link()
            current.set_link(temp)
Exemplo n.º 22
0
 def partition(self, head: ListNode, x: int) -> ListNode:
     dummy1, dummy2 = ListNode(), ListNode()
     cur1, cur2, cur = dummy1, dummy2, head
     while cur:
         if cur.val < x:
             cur1.next = cur
             cur1 = cur1.next
         else:
             cur2.next = cur
             cur2 = cur2.next
         cur = cur.next
     cur1.next = dummy2.next
     cur2.next = None
     return dummy1.next
Exemplo n.º 23
0
 def solution(self, head, x):
     l = left = ListNode(-1)
     r = right = ListNode(-1)
     while head:
         if head.val < x:
             l.next = head
             l = l.next
         else:
             r.next = head
             r = r.next
         head = head.next
     r.next = None
     l.next = right.next
     newHead = left.next
     return newHead
Exemplo n.º 24
0
 def addTwoNumbers(self, l1, l2):
     carry = 0
     root = n = ListNode(0)
     while l1 or l2 or carry:
         v1 = v2 = 0
         if l1:
             v1 = l1.val
             l1 = l1.next
         if l2:
             v2 = l2.val
             l2 = l2.next
         carry, val = divmod(v1 + v2 + carry, 10)
         n.next = ListNode(val)
         n = n.next
     return root.next
Exemplo n.º 25
0
 def reverseBetween(self, head, m, n):
     """
     :type head: ListNode
     :type m: int
     :type n: int
     :rtype: ListNode
     """
     if m == n:
         return head
     res_node = ListNode.ListNode(0)
     res_node_last = res_node
     index = 1
     current = head
     restnode = None
     while current:
         if index == m:
             while index < n:
                 current = current.next
                 index += 1
             restnode = current.next
             temp = head
             index = 1
             while index < m:
                 temp = temp.next
                 index += 1
             prenode = ListNode.ListNode(temp.val)
             temp = temp.next
             index += 1
             if n - m > 1:
                 nextnode = temp.next
                 temp = ListNode.ListNode(temp.val)
                 while index < n:
                     temp.next = prenode
                     prenode = temp
                     temp = ListNode.ListNode(nextnode.val)
                     nextnode = nextnode.next
                     index += 1
             temp.next = prenode
             res_node_last.next = temp
             while temp.next:
                 temp = temp.next
             temp.next = restnode
             return res_node.next
         else:
             res_node_last.next = ListNode.ListNode(current.val)
             res_node_last = res_node_last.next
             current = current.next
             index += 1
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre = ListNode(0)

        right = head
        while right is not None:
            temp = right.next  # temp saves the next node of right
            right.next = None  # disconnect "right" with the next

            # search from pre, and 'left" will stop at the node before the correct insertion position
            left = pre
            while left.next is not None and left.next.val < right.val:
                left = left.next

            # insert the 'right' node
            next = left.next
            left.next = right
            right.next = next

            # advance the 'right' iterator
            right = temp

        return pre.next
Exemplo n.º 27
0
    def goElsewhere(self, resource, usecache=1, *args):
        """This is a wrapper for dealing with the download thread.  Pass it
        one resource as an argument, and that resource will be downloaded in
        the background.  Optionally, if the file exists in the cache, it will
        be loaded from there if usecache is true."""

        self.resource = resource
        self.response = None
        optionsUseCache = Options.program_options.getOption("use_cache")

        # Attempt to load the response object out of the cache.
        if usecache and optionsUseCache and not resource.getDataBlock():
            # Don't try to pull something out of cache unless it doesn't have
            # a data block. If it does, we have to submit information
            utils.msg(self.mb, "Looking for document in cache...")
            self.response = Options.program_options.cache.uncache(resource)

        if not self.response:
            utils.msg(self.mb, "Document not in cache. Fetching from network.")
            # We need to fetch this document from the network.
            # Signal the download thread to go to work, and get out.
            newthread = Thread(group=None,
                               target=self.downloadResource,
                               name="Download Thread",
                               args=(self.resource, ))
            # Thread is responsible for adding the resource to the queue list
            newthread.start()
            return
        else:
            utils.msg(self.mb, "Loading document from cache to display.")
            self.createResponseWidget()
            s = State.State(self.response, self.resource, self.child)
            self.navList.insert(ListNode.ListNode(s))
            self.changeContent(self.child)
        return None
Exemplo n.º 28
0
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if head == None or head.next == None:
            return head

        length = 0
        dummy = ListNode(-1)
        dummy.next = head

        cur = dummy.next
        while cur:
            length += 1
            cur = cur.next
        k = k % length

        p, q = dummy, dummy
        for i in range(k):
            q = q.next

        while q.next:
            p, q = p.next, q.next

        q.next = dummy.next
        dummy.next = p.next
        p.next = None
        return dummy.next
Exemplo n.º 29
0
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or not head.next:
            return head

        pre = self
        pre.next = head
        dummy = ListNode(0)
        count = 1
        while head.next:
            count += 1
            head = head.next
        if count == k:
            return self.next
        head.next = self.next
        head = self.next
        step = 1
        print(count)
        while step < count - (k % count):
            head = head.next
            step += 1

        pre.next = head.next
        head.next = None
        return pre.next
Exemplo n.º 30
0
 def reverseBetween2(self, head: ListNode, m: int, n: int) -> ListNode:
     fakeHead = ListNode(0)
     fakeHead.next = head
     # find the pre node (whose next is mth node) and the tail node (nth node)
     pre, tail = fakeHead, None
     node = fakeHead  # iterator
     for step in range(1, n + 1):
         node = node.next
         if step == m - 1:
             pre = node
         if step == n:
             tail = node
     # get the head (mth node)
     head = pre.next
     pre.next = None  # disconnect pre and this section of list
     temp = tail.next  # temporarily save tail.next to be connected in future
     tail.next = None  # disconnect tail with temp
     # reverse the partial list
     pre1, node = None, head
     while node:
         t = node.next
         node.next = pre1
         pre1 = node
         node = t
     # connect pre with the new head (previous tail)
     pre.next = tail
     # connect new tail (previous head) with temp
     head.next = temp
     return fakeHead.next