Exemple #1
0
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        if head is None or head.next is None or m == n:
            return head
        headnode = ListNode(-1)
        headnode.next = head
        anchor = headnode
        for _ in range(m - 1):
            anchor = anchor.next
        a = anchor.next
        b = a.next
        c = b.next

        k = n - m
        for _ in range(k):
            b.next = a
            if c:
                a, b, c = b, c, c.next
            else:
                a, b = b, c
        anchor.next.next = b
        anchor.next = a
        return headnode.next
Exemple #2
0
 def addAtHead(self, val):
     """
     Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
     :type val: int
     :rtype: void
     """
     newnode = ListNode(val)
     newnode.next, self.headnode.next = self.headnode.next, newnode
     if self.length == 0:
         self.tail = newnode
     self.length += 1
Exemple #3
0
 def deleteDuplicates(self, head):
     """
     :type head: ListNode
     :rtype: ListNode
     """
     headnode = ListNode(None)
     headnode.next = head
     delete = False
     p = headnode  # prev
     c = head  # current
     while c:
         while c.next and c.val == c.next.val:
             c.next = c.next.next
             if not delete:
                 delete = True
         if delete:
             c = c.next
             p.next = c
             delete = False
         else:
             c = c.next
             p = p.next
     return headnode.next
Exemple #4
0
 def addAtIndex(self, index, val):
     """
     Add a node of value val before the index-th node in the linked list. 
     If index equals to the length of linked list, the node will be appended to the end of linked list. 
     If index is greater than the length, the node will not be inserted.
     :type index: int
     :type val: int
     :rtype: void
     """
     if index < 0 or index > self.length:
         return None
     if index == 0:
         self.addAtHead(val)
     elif index == self.length:
         self.addAtTail(val)
     else:
         insert_point = self._get(index)
         newnode = ListNode(insert_point.val)
         newnode.next = insert_point.next
         insert_point.next = newnode
         insert_point.val = val
         self.length += 1
         if insert_point is self.tail:
             self.tail = insert_point.next