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