Beispiel #1
0
def reverseKGroup(head, k):
    """
    :type head: ListNode
    :type k: int
    :rtype: ListNode
    """
    helper = ListNode(0)
    helper.next = head
    pre, tail = helper, helper
    count = 0
    while tail:
        tail = tail.next
        count += 1
        if (
                count == k
        ) and tail:  # bug fixed --- need to reconsider tail if it has been updated. consider the case 1->2->None with k = 3
            nextHead = tail.next  # temporarily save the next group's head
            (newHead, newTail) = reverseKGroup2(head, tail,
                                                k)  # swap this k group nodes
            pre.next = newHead  # link the pre node with the new head
            newTail.next = nextHead  # link the new tail with the previously saved next group's head
            pre = newTail  # update pre node
            head = nextHead  # update head node
            tail = newTail  # update tail node
            count = 0

    return helper.next
Beispiel #2
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 return_linear_list(head):
    ## find if cyclic or not
    tup1 = floyds_2pointer_steps(head)
    if tup1[0] == -1:
        return head

    tup2 = floyds_2pointer_steps(tup1[1])
    ##find the no of nodes in cycle
    nNodesInCycle = tup2[0]
    

    ##find the point of repetition
    p1 = head
    p2= head
    count = 1
    while True:
        if p2.next == p1:
            p2.next = None
            if (count-nNodesInCycle)%2 == 1:
                n = ListNode('added')
                n.next = p1
                return n
            else:
                return p1
        if count<nNodesInCycle:
            p2=p2.next
        else:
            p1=p1.next
            p2 = p2.next
        count+=1
Beispiel #4
0
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if k == 0 or not head or head.next is None:
            return head

        # helper node to handle the new head case
        pre = ListNode(0)
        pre.next = head

        tail, l = pre, 0
        while tail.next is not None and l < k:  # When while condition fails, tail is either on "tail" node, or l == k, which means tail is on the ready to move position
            l += 1
            tail = tail.next

        if tail.next is None:  # if tail is on "tail", this means k >= l, so we need to put the tail back on k%l position
            k = k % l
            tail = pre
            for i in range(k):
                tail = tail.next

        helper = pre
        while tail.next is not None:  # After this, helper's next will point to the start node of the section to be rotated to the beginning
            helper = helper.next
            tail = tail.next

        tail.next = pre.next
        pre.next = helper.next
        helper.next = None

        return pre.next
Beispiel #5
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
Beispiel #6
0
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        def reverse(head):
            pre = None
            curr = head
            while curr:
                next = curr.next
                curr.next = pre
                pre = curr
                curr = next
            return pre

        dummy = ListNode(-1)
        dummy.next = head
        # pre:指向待翻转区域的前一个节点
        # end:指向待翻转区域的最后一个节点
        # next:指向待翻转区域的后一个节点,即end.next
        pre, end = dummy, dummy
        while end.next:
            i = 0
            while i < k and end:
                end = end.next
                i += 1

            if end == None:
                break

            start = pre.next
            next = end.next
            end.next = None
            pre.next = reverse(start)
            start.next = next
            pre = start
            end = pre

        return dummy.next
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or head.next is None:
            return head

        pre = ListNode(0)
        pre.next = head

        num = head.val
        left, right, node = pre, head.next, head  # node is the candidate ListNode to be linked to left
        while right:
            if right.val == num:
                node = None
            else:
                if node:
                    left.next = node
                    left = left.next

                node = right
                num = right.val

            right = right.next

        if node:  # bug fixed here: forgot the remaining node when "while" loop ends
            left.next = node
            node.next = None
        else:
            left.next = None

        return pre.next
    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
Beispiel #9
0
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        helper = ListNode(0)
        helper.next = head

        pre = helper
        for i in range(m - 1):
            pre = pre.next

        # Now pre.next will be the 1st node to be reversed
        head, left, right = pre.next, pre.next, pre.next.next
        for j in range(n - m):
            temp = right.next
            right.next = left
            left = right
            right = temp

        pre.next = left
        head.next = right

        return helper.next
Beispiel #10
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
Beispiel #11
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
Beispiel #12
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
Beispiel #13
0
    def addTwoNumbers_in_order_result(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 or not l2:
            return l1 or l2

        cur = self

        carry = 0
        pre = None
        while l1 or l2 or carry:
            if l1:
                carry = carry + l1.val
                l1 = l1.next
            if l2:
                carry = carry + l2.val
                l2 = l2.next
            temp = ListNode(carry % 10)

            temp.next = pre
            cur.next = temp
            pre = temp
            carry = carry // 10
        return cur
Beispiel #14
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
Beispiel #15
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
 def sortList(self, head: ListNode) -> ListNode:
     if not head or not head.next:
         return head
     
     pseudoHead = ListNode(0)
     pseudoHead.next = head
     # find the mid node
     fast, mid = pseudoHead, pseudoHead
     while fast and fast.next:
         fast = fast.next.next
         mid = mid.next
         
     right, mid.next = mid.next, None
     # recursively sort left and right part
     left, right = self.sortList(head), self.sortList(right)
     
     pre = pseudoHead
     # merge two lists
     while left or right:
         lVal = 2**31 if not left else left.val
         rVal = 2**31 if not right else right.val
         if lVal < rVal:
             pre.next = left
             left = left.next
         else:
             pre.next = right
             right = right.next
         pre = pre.next
     
     return pseudoHead.next
 def reverseList2(self, head):
     l = None
     while not head == None:
         l2 = ListNode(head.val)
         l2.next = l
         l = l2
         head = head.next
     return l
 def reverseList2(self, head):
     l = None
     while not head == None:
         l2 = ListNode(head.val)
         l2.next = l
         l = l2
         head = head.next
     return l
    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)
Beispiel #20
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
Beispiel #21
0
 def removeElements(self, head, val):
     root = ListNode(0)
     root.next = head
     travel = root
     while travel.next:
         if travel.next.val == val:
             travel.next = travel.next.next
         travel = travel.next
     return root.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)
Beispiel #23
0
    def sortList(self, head:ListNode) -> ListNode:
        # h:指向未归并链表头部
        # length:链表总长度
        # inv:归并链表的长度
        h, length, intv = head, 0, 1

        # 计算length
        while h:
            h, length = h.next, length+1

        # 虚拟头结点
        res = ListNode(-1)
        res.next = head

        while intv < length:
            # pre:指向待归并链表的前一个节点
            pre, h = res, res.next
            while h:
                # 获取两个归并链表的头节点h1,h2
                # 获取h1
                h1, i = h, intv
                while i and h:
                    h, i = h.next, i-1

                # h1指向的链表不足inv,无需归并
                if i:
                    break

                # 获取h2和h2链表长度, 更新h
                h2, i = h, intv
                while i and h:
                    h, i = h.next, i-1

                # 归并h1、h2
                c1, c2 = intv, intv - i
                while c1 and c2:
                    if h1.val < h2.val:
                        pre.next = h1
                        h1 = h1.next
                        c1 -= 1
                    else:
                        pre.next = h2
                        h2 = h2.next
                        c2 -= 1
                    pre = pre.next

                pre.next = h1 if c1 else h2

                # 归并剩余
                while c1>0 or c2>0:
                    pre = pre.next
                    c1 -= 1
                    c2 -= 1
                pre.next = h
            intv = intv*2
        return res.next
Beispiel #24
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
 def solution(self, head):
     if not head: return False
     newHead = ListNode(-1)
     newHead.next = head
     slow = newHead
     fast = newHead.next
     while slow and fast and fast.next:
         if slow == fast: return True
         slow = slow.next
         fast = fast.next.next
     return False
Beispiel #26
0
 def hasCycle(self, head):
     if not head: return False
     newHead = ListNode(-1)
     newHead.next = head
     slow = newHead
     fast = newHead.next
     while slow and fast and fast.next:
         if hash(slow) == hash(fast): return slow
         slow = slow.next
         fast = fast.next.next
     return False
 def hasCycle(self, head):
     if not head: return False
     newHead = ListNode(-1)
     newHead.next = head
     slow = newHead
     fast = newHead.next
     while slow and fast and fast.next:
         if hash(slow) == hash(fast): return slow
         slow = slow.next
         fast = fast.next.next
     return False
Beispiel #28
0
 def solution(self, head):
     if not head: return False
     newHead = ListNode(-1)
     newHead.next = head
     slow = newHead
     fast = newHead.next
     while slow and fast and fast.next:
         if slow == fast: return True
         slow = slow.next
         fast = fast.next.next
     return False
    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
    def countNodes(self, head):
        # write your code here
        dummy = ListNode(0)
        dummy.next = head
        head = dummy

        count = 0
        while head.next:
            count += 1
            head = head.next

        return count
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 removeElements(self, head: ListNode, val: int) -> ListNode:
        dummy_Head = ListNode(-1)
        dummy_Head.next = head

        cur = dummy_Head
        while cur.next != None:
            if cur.next.val == val:
                # 删除cur.next
                cur.next = cur.next.next
            else:
                cur = cur.next
        return dummy_Head.next
Beispiel #33
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
Beispiel #34
0
 def solution(self, head):
     visited = set()
     if not self.hasCycle(head): return None
     newHead = ListNode(-1)
     newHead.next =head
     while newHead is not None:
         key = hash(newHead)
         if key in visited:
             break
         else:
             visited.add(key)
         newHead = newHead.next
     return newHead
 def solution(self, head, val):
     if not head: return head
     top = ListNode(0)
     top.next = head
     prev = head = top
     while top:
         if top.val == val:
             if top.next:
                 top.val = top.next.val
                 top.next = top.next.next
             else:
                 prev.next = None
                 break
         else:
             prev = top
             top = top.next
     return head.next
Beispiel #36
0
 def getIntersectionNode(headA, headB):
     """
     :type head1, head1: ListNode
     :rtype: ListNode
     """
     if headA == None or headB == None:
         return None
     else:
         temp = ListNode(0)
         temp.next = headB
         while headA.next != None:
             while headB.next!=None:
                 if headB.next.val==headA.next.val:
                     return headA.next
                 headB = headB.next
             headA = headA.next
             headB = temp.next
         return None
 def deleteDuplicates(self, head):
     sentry = ListNode(0)
     sentry.next = head
     
     p = sentry.next
     prev = sentry.next
     
     while p:
         if p.val == prev.val:
             p = p.next
             continue
         
         prev.next = p
         prev = p
         p = p.next
     
     if prev:    
         prev.next = p
     
     return sentry.next
    def removeNthFromEnd(self, head, n):
        if head == None: return None
        if head.next == None and n == 1: return None

        dummyHead = ListNode(-1)
        dummyHead.next = head
        prev = dummyHead;
        cur = head;

        while n > 0 and cur != None:
            cur = cur.next
            n -= 1

        if n > 0: return head

        while cur != None:
            prev = prev.next
            cur = cur.next

        prev.next = prev.next.next

        return dummyHead.next
Beispiel #39
0
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prehead = ListNode(None)
        prehead.next = head
        preptr = prehead
        ptr = head
        stack = []
        while ptr != None:
            stack.append(ptr)
            ptr = ptr.next
            # print ptr if ptr is None else ptr.val
            if len(stack) == 2:
                preptr.next = stack.pop()
                preptr.next.next = stack.pop()
                preptr = preptr.next.next
        if len(stack) == 1:
            preptr.next = stack.pop()
            preptr = preptr.next
        preptr.next = None

        return prehead.next
    def sortedListToBST(self, head):
        if not head:
            return head
        slow = head
        fast = head
        pre = None
        while fast.next and fast.next.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next

        if pre is not None:
            pre.next = None
        else:
            head = None
        root = TreeNode(slow.val)
        root.left = self.sortedListToBST(head)
        root.right = self.sortedListToBST(slow.next)
        return root

from ListNode import *
from TreeNode import *
node1 = ListNode(1)
node2 = ListNode(3)
node3 = ListNode(1)

node1.next = node2

solu = Solution()
tree = solu.sortedListToBST(node1)
print 'ok'
 def reverseList(self, head):
     dummy = ListNode(float("-inf"))
     while head:
         dummy.next, head.next, head = head, dummy.next, head.next
     return dummy.next
 def removeNthFromEnd(self, head, n):
     # create a forward pointer and a sentry
     forward = head
     sentry = ListNode(0)
     sentry.next = head
     curr = sentry
     
     # move a forward pointer
     for _ in range(0, n):
         forward = forward.next
         
     # move both at the same time
     while forward:
         forward = forward.next
         curr = curr.next
         
     # remove element
     curr.next = curr.next.next
     
     return sentry.next