def add_item_at_index(self, index, data): new_node = LinkedListNode(data) self.count += 1 if self.head is None: self.head = new_node self.tail = new_node return node = self.head prev = None for i in range(0, index): prev = node node = node.next if node is None: break if prev: prev.next = new_node new_node.prev = prev else: self.head.prev = new_node new_node.next = self.head self.head = new_node if node: node.prev = new_node new_node.next = node else: self.tail = new_node
def rev_num_items_in_list(self, number_items_to_reverse): if number_items_to_reverse >= self.count: return False stack = LinkedStack() node = self.head for i in range(0, number_items_to_reverse): stack.push(node.value) if node.next is not None: node = node.next rest_of_list = node print("Stack: ") stack.print_list() self.head = None prev = None while True: new_node = LinkedListNode(stack.pop()) if self.head is None: self.head = new_node prev = new_node else: prev.next = new_node new_node.prev = prev prev = new_node if stack.is_empty(): break prev.next = rest_of_list rest_of_list.prev = prev return True
def add_item_bottom(self, data): new_node = LinkedListNode(data) self.count += 1 if self.head is None: self.head = new_node self.tail = new_node return new_node.prev = self.tail self.tail.next = new_node self.tail = new_node