def insertAtHead(self, item): ''' pre: an item to be inserted into list post: item is inserted into beginning of list ''' node = ListNode(item) if not self.length: # set the cursor to the head because it's the # first item inserted into the list self.head = node elif self.length == 1 and not self.tail: self.tail = self.head node.link = self.tail self.head = node else: node.link = self.head self.head = node # set the cursor to the head if it's not set yet if not self.cursor: self.cursor = self.head self.length += 1
def insertAtHead(self, item): '''post: item is inserted at beginning of the list (before the current head)''' newNode = ListNode(item) if self.head is None: self.head = newNode self.cursor = newNode self.tail = newNode self.length = 1 else: newNode.link = self.head self.head = newNode self.length += 1
def insertAfterCursor(self, item): 'post: item is inserted after the cursor position' newNode = ListNode(item) if self.cursor is None: self.head = newNode self.cursor = newNode self.tail = newNode elif self.cursor is self.tail: self.cursor.link = newNode self.tail = newNode else: newNode.link = self.cursor.link self.cursor.link = newNode self.length += 1