Data structures in Python, Series 1.1: Linked Lists
Please read the Data structures in Python, Series 1: Linked Lists before starting Series 1.1 linked list
Adding elements at the start IN python :
In the previous example we learnt how to make a simple node in python and add elements in the node and how to join them.
Now we are going to write a bit advanced code than the previous one. We will be adding more attributes to the node and will make the appending task a little tricky by adding the elements at the beginning . Thanks to pythoncentral
So have fun :
# Firt of all make a node class for every future node to be shaped like .
# Firt of all make a node class for every future node to be shaped like .
class node():
def __init__(self,data,nextnode = None):
self.data = data
self.nextnode = nextnode
#now make a class with the all the operations that can be operated in a list
#remember do get a __init__ as this will be used to initiate the default values for the instance in main
class linkedlist():
def __init__(self):
self.head = None
self.data = 0
self.size = 0
def addnode(self,data):
self.data = data
new = node(data,self.head)
self.head = new
self.size +=1
def __print__(self):
cur = self.head
while cur:
print(str(cur.data),end = '>>')
cur = cur.nextnode
print('None')
if __name__ == '__main__':
lis = linkedlist()
for i in range(int(input('enter the number of elements to be inserted'))):
lis.addnode(int(input('enter the value')))
lis.__print__()
Comments
Post a Comment