def prepend(self, data): if self.head == None: self.head = Node(data) else: new_head = Node(data) new_head.next = self.head self.head = new_head
def insert_after(self, locdata, data): node = Node(data) curr = self.head while curr.data != locdata and curr.next: curr = curr.next node.next = curr.next curr.next = node
def push(self, new_data): # Create new node new_node = Node(new_data) # Make next of new node as head new_node.next = self.head # Point new node the head node self.head = new_node
def insert_at_head(self, data): if self.head is None: self.head = Node(data) return node = Node(data) self.head.prev = node node.next = self.head self.head = node
def insert_at_pos(self, pos, data): node = Node(data) curr = self.head count = 1 while count != pos and curr.next: curr = curr.next count += 1 node.next = curr.next curr.next = node
def add_to_front(self, item): temp = Node(item) if self.back == None: self.back = self.front = temp return oldfront = self.front self.front = temp temp.next = oldfront self.n += 1
def createList(iterator) -> Node: ''' Create a link list with None head and keep the order. ''' head = Node(None, None) head.next = head probe = head for data in iterator: probe.next = Node(data, head) probe = probe.next # node head return head
def insertAfter(self, prev_node, new_data): # Check if the given prev_node exists if prev_node is None: print("Prev node must be in list") return # Create a new node new_node = Node(new_data) # Make next of new node as next of prev_node new_node.next = prev_node.next prev_node.next = new_node
def insert_at(self, item, i): insert = Node(item) if i == 0: self.add_to_front(item) return elif i > self.n: self.add_to_back(item) return x = 0 curr = self.front while x < i - 1: # get left neighbor curr = curr.next x += 1 next_one = curr.next curr.next = insert insert.next = next_one self.n += 1
def insert_at_head(self, data): node = Node(data) node.next = self.head self.head = node