class LinkedList():
def __init__(self, value_first_item):
self.head = {
"value": value_first_item,
"next": None,
}
self.length = 1
self.tail = self.head
def get_head(self):
return self.head["value"]
def get_tail(self):
return self.tail["value"]
def append(self, value):
new_node = {
"value": value,
"next": None,
}
self.tail["next"] = new_node
self.tail = new_node
self.length+=1
def prepend(self, value):
new_node = {
"value": value,
"next": self.head,
}
self.head = new_node
self.length+=1
def get_position(self, position):
""" get the value of a specific position in the linked list."""
if position < 0:
raise IndexError("No negative positions")
if position > self.length:
raise IndexError("Position out of boundaries")
elif position == self.length:
return self.get_tail()
elif position == 0:
return self.get_head()
element = self.head["next"]
curr_position = 1
if element != None:
if position == 1:
return element["value"]
else:
while element["next"] != None:
element = element["next"]
curr_position+=1
if curr_position == position:
break
return element["value"]
print("Hello World!")
myLinkedList = LinkedList(5)
print(myLinkedList.get_head())
print(myLinkedList.get_tail())
myLinkedList.append(10)
myLinkedList.append(15)
print(myLinkedList.get_head())
assert(myLinkedList.get_head() == 5)
print(myLinkedList.get_tail())
print(myLinkedList.get_position(1))
myLinkedList.append(20)
print(myLinkedList.get_position(3))
print(myLinkedList.get_position(4))
assert(myLinkedList.get_position(4) == 20)
myLinkedList.prepend(2)
assert(myLinkedList.get_head() == 2)
assert(myLinkedList.get_position(0) == 2)
print("Good-bye Cruel World")