Linked list
unknown
python
3 years ago
2.8 kB
3
Indexable
Never
class Element(): def __init__(self, value): self.value = value self.next = None class LinkedList(): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element def get_position(self, position): """Get an element from a particular position. Assume the first position is "1". Return "None" if position is not in the list.""" current = self.head counter = 1 while current: if counter == position: return current elif counter > position: return None else: counter += 1 current = current.next def insert(self, new_element, position): """Insert a new node at the given position. Assume the first position is "1". Inserting at position 3 means between the 2nd and 3rd elements.""" current = self.head position_found = False counter = 1 if position == 1: self.head = new_element self.head.next = current return while not position_found: if counter == position-1: position_found = True new_element.next = current.next current.next = new_element return else: current = current.next counter += 1 def delete(self, value): """Delete the first node with a given value.""" current = self.head previous = None if current.value == value: self.head = current.next return while current.next: if current.value == value: previous.next = current.next previous = current current = current.next return # Test cases # Set up some Elements e1 = Element(1) e2 = Element(2) e3 = Element(3) e4 = Element(4) # Start setting up a LinkedList ll = LinkedList(e1) ll.append(e2) ll.append(e3) # Test get_position # Should print 3 # print(ll.head.next.next.value) # # Should also print 3 # print(ll.get_position(3).value) # Test insert ll.insert(e4, 3) # Should print 4 now # print(ll.get_position(3).value) # Test delete ll.delete(1) # Should print 2 now print (ll.get_position(1).value) # Should print 4 now print (ll.get_position(2).value) # Should print 3 now print (ll.get_position(3).value)