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_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 add_item_top(self, data): new_node = LinkedListNode(data) if self.head is not None: new_node.next = self.head self.head.prev = new_node else: self.tail = new_node self.head = new_node self.count += 1
def add_item_top(self, data): new_node = LinkedListNode(data) if self.head is not None: new_node.next = self.head self.fix_tail(self.head, new_node) else: new_node.next = new_node self.head = new_node self.count += 1
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
def add_item_bottom(self, data): new_node = LinkedListNode(data) self.count += 1 if self.head is None: self.head = new_node new_node.next = self.head return node = self.head while node.next is not self.head: node = node.next node.next = new_node new_node.next = self.head
def add_item_at_index(self, index, data): new_node = LinkedListNode(data) self.count += 1 if self.head is None: self.head = new_node new_node.next = self.head return node = self.head prev = None for i in range(0, index): prev = node node = node.next #in the case of being at the bottom of the list we want prev to be the last element, so node will be head. if node == self.head: break if prev: prev.next = new_node else: self.fix_tail(self.head, new_node) self.head = new_node if node != self.head: new_node.next = node else: new_node.next = self.head
def push(self, data): node = LinkedListNode(data) if self.head: node.next = self.head self.head = node self.num_items += 1