def push(self, data): node = Node(data) if self.isEmpty(): self.top = node return node.next = self.top self.top = node
def insert(self, index, data): node = Node(data=data) cur_node = self.head cur_index = 0 while cur_index < index - 1 and cur_node is not None: #O(n) cur_node = cur_node.next cur_index += 1 node.next = cur_node.next cur_node.next = node
def prepend(self, data): node = Node(data=data) if self.head is None: self.head = node self.head.next = None if self.tail is None: self.tail = node self.tail.next = None else: node.next = self.head self.head = node
p2 = LL.head found_dup = False while p2 is not p1: if id(p2.data) == id(p1.data): print("we found the same data") found_dup = True break if not found_dup: print 'no duplicate yet', p1.data, p1.next.data p1 = p1.next else: print 'duplicate ', p1.data, p1.next.data p1 = p1.next LL.tail = p1 node_a = Node('data') node_b = Node('alex') node_c = Node('alex') node_d = Node('hello') node_b.next = node_c node_c.next = node_d linked_list = LinkedList() linked_list.head = node_b remove_dups_constant_space(linked_list) print len(linked_list) print(linked_list.head.data) print(linked_list.head.next.data)
def prepend(self, data): newHead = Node(data) newHead.next = self.head self.head = newHead