Skip to content

Instantly share code, notes, and snippets.

@prat0318
Created November 10, 2013 19:16
Show Gist options
  • Save prat0318/7402512 to your computer and use it in GitHub Desktop.
Save prat0318/7402512 to your computer and use it in GitHub Desktop.
single linked list with insert, pop and print operations
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