Tuesday, March 30, 2010

Stack Implemented as a LinkedList in Python

In preparation for interviews, I am attempting to write a Stack as a LinkedList in python. This is what I came up with:
 class Stack:  
class Element:
def __init__(self, data=None, next=None):
self.next = next
self.data = data

def __repr__(self):
return str(self.data)

def __init__(self):
self.head = self.Element()

def push(self, data):
newHead = self.Element(data=data, next=self.head)
self.head = newHead

def pop(self):
head = self.head
self.head = head.next
return head

def delete(self):
self.head = None

If anyone sees anything wrong, please let me know!

No comments:

Post a Comment