-
Notifications
You must be signed in to change notification settings - Fork 1
/
stack_using_linked_list.py
55 lines (40 loc) · 1.19 KB
/
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
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.head = None
self.num_elements = 0
def push(self, value):
new_node = Node(value)
if self.head:
new_node.next = self.head
self.head = new_node
self.num_elements += 1
def peek(self):
if self.is_empty():
return None
return self.head.value
def pop(self):
if self.is_empty():
return
value = self.head.value
self.head = self.head.next
return value
def size(self):
return self.num_elements
def is_empty(self):
return self.num_elements == 0
# Test case
stack = Stack()
for i in range(10):
stack.push(f"Elem{i}")
print ("Pass" if (stack.size() == 10) else "Fail")
print ("Pass" if (stack.peek() == "Elem9") else "Fail")
stack.push("Elem60")
print ("Pass" if (stack.pop() == "Elem60") else "Fail")
print ("Pass" if (stack.pop() == "Elem9") else "Fail")
print ("Pass" if (stack.pop() == "Elem8") else "Fail")
stack.push(50)
print ("Pass" if (stack.size() == 12) else "Fail")