|
| 1 | +""" Use LinkedList class to implement a Stack. """ |
| 2 | + |
| 3 | +class Element(object): |
| 4 | + def __init__(self, value): |
| 5 | + self.value = value |
| 6 | + self.next = None |
| 7 | + |
| 8 | +class LinkedList(object): |
| 9 | + def __init__(self, head=None): |
| 10 | + self.head = head |
| 11 | + |
| 12 | + def append(self, new_element): |
| 13 | + current = self.head |
| 14 | + if self.head: |
| 15 | + while current.next: |
| 16 | + current = current.next |
| 17 | + current.next = new_element |
| 18 | + else: |
| 19 | + self.head = new_element |
| 20 | + |
| 21 | + def insert_first(self, new_element): |
| 22 | + "Insert new element as the head of the LinkedList" |
| 23 | + # fetch the current head |
| 24 | + current = self.head |
| 25 | + new_element.next = current |
| 26 | + self.head = new_element |
| 27 | + |
| 28 | + def delete_first(self): |
| 29 | + "Delete the first (head) element in the LinkedList and return it" |
| 30 | + current = self.head |
| 31 | + if current: |
| 32 | + if current.next: |
| 33 | + self.head = current.next |
| 34 | + else: |
| 35 | + self.head = None |
| 36 | + return current |
| 37 | + else: |
| 38 | + return None |
| 39 | + |
| 40 | +class Stack(object): |
| 41 | + def __init__(self,top=None): |
| 42 | + self.ll = LinkedList(top) |
| 43 | + |
| 44 | + def push(self, new_element): |
| 45 | + "Push (add) a new element onto the top of the stack" |
| 46 | + self.ll.insert_first(new_element) |
| 47 | + |
| 48 | + def pop(self): |
| 49 | + "Pop (remove) the first element off the top of the stack and return it" |
| 50 | + return self.ll.delete_first() |
| 51 | + |
| 52 | +# Test cases |
| 53 | +# Set up some Elements |
| 54 | +e1 = Element(1) |
| 55 | +e2 = Element(2) |
| 56 | +e3 = Element(3) |
| 57 | +e4 = Element(4) |
| 58 | + |
| 59 | +# Start setting up a Stack |
| 60 | +stack = Stack(e1) |
| 61 | + |
| 62 | +# Test stack functionality |
| 63 | +stack.push(e2) |
| 64 | +stack.push(e3) |
| 65 | +print stack.pop().value |
| 66 | +print stack.pop().value |
| 67 | +print stack.pop().value |
| 68 | +print stack.pop() |
| 69 | +stack.push(e4) |
| 70 | +print stack.pop().value |
0 commit comments