Example #1
0
    def addAtIndex(self, index, val):
        h = self.head
        now = 0
        while h:
            if index == now:
                break
            h = h.next
            now += 1
        if h is not None:

            temp = ListNode(val)
            temp.next = h.next
            h.next = temp
            if temp.next is None:
                self.tail = temp
Example #2
0
 def splitListToParts(self, root, k):
     size = 0
     h = root
     while h:
         h = h.next
         size += 1
     length = int(size / k)
     r = [length for i in range(k)]
     left = size - length * k
     for i in range(left):
         r[i] += 1
     head = ListNode(0)
     head.next = root
     re = []
     for i in r:
         re.append(head.next)
         temp = head
         for j in range(i):
             head = head.next
         temp.next = None
     return re
 def insertionSortList(self, head):
     sort = ListNode(0)
     while head:
         temp = sort
         while temp.next:
             if temp.next.val > head.val:
                 break
         tmp = head.next
         head.next = temp.next
         temp.next = head
         head = tmp
     return sort.next
Example #4
0
 def reorderList(self, head):
     if head is None:
         return None
     tmp = ListNode(0)
     tmp.next = head
     fast, slow = tmp, tmp
     while fast and fast.next:
         fast = fast.next.next
         slow = slow.next
     min = slow
     slow = slow.next
     stack = []
     while slow:
         stack.append(slow)
         slow = slow.next
     stack.reverse()
     for s in stack:
         s.next = head.next
         head.next = s
         head = s.next
     head.next = None
     head = tmp.next
Example #5
0
 def oddEvenList(self, head):
     l = ListNode(0)
     r = ListNode(0)
     l1, r1 = l, r
     s = 0
     while head:
         s += 1
         if s % 2 == 1:
             l.next = head
             l = head
         else:
             r.next = head
             r = head
         head = head.next
     l.next = r1.next
     r.next = None
     return l1.next
Example #6
0
 def __init__(self):
     self.head = ListNode(0)
     self.tail = self.head
Example #7
0
 def addAtTail(self, val):
     temp = ListNode(val)
     self.tail.next = temp
     self.tail = temp