``````class List():
def __init__(self,values=0):
self.numb=values
self.numb=values
def show(self):
print self.numb

In main call i want some thing like this

``````list1=List()
list1.add(43) #i want to add numbers to liked list node like this
list1.show()#Then retrieve it from the linked list(list1)``````

I am not sure about the logic because when i want to add third number it just saves it to the 2nd node of the linked list ,so more precisly its storing first list.add(43) and list.add(938) where is list1.add(22) gone ? ...Please write some code and explain so that i can add more numbers and display them using Obj.add() and Obj.show() Notation ..Thanks in advance

## All 2 Replies

In a traditional implementation of linked lists, one distinguishes lists and list elements, so you will have 2 classes like this

``````class Element(object):
__slots__ = ("numb", "next")

def __init__(self, numb):
self.numb = numb
self.next = None

class List(object):
__slots__ = ("first", "last")

def __init__(self):
self.first = self.last = None

if self.first is None:
self.first = self.last = Element(numb)
else:
self.last.next = Element(numb)
self.last = self.last.next

def show(self):
elt = self.first
print "showing list"
while elt is not None:
print elt.numb
elt = elt.next

list1 = List()
list1.show()
list1.show()

""" my output -->
showing list
showing list
43
22
938
"""``````

Also note that this implementation is naive and inefficient in python. Python already contains a class of doubly linked lists, namely `collections.deque` which will most certainly be faster than your own implementation in pure python.

I think a good start for a linked list class would be to have a Node class and have the list be made up of Node objets.

``````class Node():
def __init__(self, val, next=None):
self.value = val
self.nextNode = next

def update(val=None, next=None):
if val:
self.value = val
if next:
self.nextNode = next``````

Edit: while I was posting my hint/pointer of sorts, Grib was giving you a full implementation. But I'll leave mine since it is a bit different that the element implementation Grib used anyway.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.