I have done the following linked list in python, it works fine, but I was wondering if there is another way to to the part add_item to a linked list. In that part what I want to do is to keep a pointer in the first element, and so adding the elements in front of it, for example:
1 first
1----->2 first
1----->2----->3 first
my code is:
class Node:
def __init__(self,elem=None,next=None):
self.elem=elem
self.next=next
def __repr__(self):
return 'Node(elem={}, next={})'.format(self.elem, self.next)
class LinkedList:
def __init__(self):
self.size=0
self.first=None
self.linkedlist=Node()
def add(self,elem):
node=Node(elem)
if self.size==0:
self.first=node
else:
self.linkedlist.next=node
self.linkedlist=node
self.size=self.size+1
is there another way to perform this behaviour wihout using the auxiliar self.linkedlist that I have in the builder of the LinkedList class?
Thanks