This is a gentle intro into data structures using python.This is my personal learning experience and to take a note of what i am learning.Please feel free to comment
In this post I have tried to implement a simple Linked List using Python.
First I have created a file named LList.py which will contain the following code.Then i would be using this as a module in my main file to create a implementation using these
In this post I have tried to implement a simple Linked List using Python.
First I have created a file named LList.py which will contain the following code.Then i would be using this as a module in my main file to create a implementation using these
#Single node creation class
class Element:
def __init__(self, x):
self.data = x
self.next = None
#Linked List implementation class
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, x):
e = Element(x)
if self.head is None:
self.head = e
self.tail = e
else:
self.tail.next = e
self.tail = e
def showlist(self):
e = self.head
while e.next is not None:
print e.data
e = e.next
print e.data
Now lets make a new file called ListMain.py and have the following code:
import LList
#Adding 5 elements to list and showing it
if __name__ == '__main__':
testList = LList.LinkedList()
testList.append(1)
testList.append(2)
testList.append(3)
testList.append(4)
testList.append(5)
testList.showlist()
Try running in command line the : python ListMain.py
Hope it was useful :)
Brilliant example to demonstrate the use of "self" in Python.
ReplyDeletePlease use a monospaced font for your code block. I think the Classic Blogger template will look much better than Dynamic Views. :)