Created
November 10, 2013 19:16
-
-
Save prat0318/7402512 to your computer and use it in GitHub Desktop.
single linked list with insert, pop and print operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class node: | |
def __init__(self, val): | |
self.value = val | |
self.next = None | |
class linked_list: | |
def __init__(self): | |
self.head = None | |
def insert(self, value): | |
if not(self.head): | |
self.head = node(value) | |
else: | |
temp = self.head | |
while(temp.next): | |
temp = temp.next | |
temp.next = node(value) | |
def print_list(self): | |
if not(self.head): | |
print "List Empty!" | |
return | |
temp = self.head | |
while(temp.next): | |
print temp.value, | |
temp = temp.next | |
print(temp.value) | |
def pop(self): | |
if not(self.head): | |
raise Exception("Cannot pop! Empty list") | |
return | |
prev_tmp = None; tmp = self.head | |
while(tmp.next): | |
prev_tmp = tmp | |
tmp = tmp.next | |
if not(prev_tmp): | |
self.head = None | |
return tmp.value | |
prev_tmp.next = None | |
return tmp.value | |
#Errors : Not using self as parameter in methods | |
#Errors : Giving data types to identifiers | |
#Errors : mentioning instance variable outside init, making them class var. | |
#Errors : while loop without incrementing | |
l = linked_list() | |
l.insert(2) | |
l.insert(3) | |
l.print_list() | |
l.insert(4) | |
l.print_list() | |
print l.pop() | |
print l.pop() | |
l.print_list() | |
print l.pop() | |
l.print_list() | |
print l.pop() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment