-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.py
More file actions
145 lines (99 loc) · 2.81 KB
/
Stack.py
File metadata and controls
145 lines (99 loc) · 2.81 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
class Node:
""" Class to define structure of each node"""
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class Stack:
"""Class to define stack structure"""
def __init__(self):
self.top = None
def getStackLength(self):
"""
This method computes the length of the linked list
Inputs:
self
Returns:
lengthCounter: Length of the linked list as an integer
"""
if self.top is None:
return 0
iterElem = self.top
lengthCounter = 0
while iterElem:
lengthCounter += 1
iterElem = iterElem.next
return lengthCounter
def push(self, data):
"""
Insert an element in the stack
Inputs:
data : Element to be inserted
Returns:
"""
insertionNode = Node(data, self.top)
self.top = insertionNode
def pop(self):
"""
Delete(pop) an element from the stack. Also display the element removed
Inputs:
Returns:
"""
if self.top is None:
raise Exception("The stack is empty. No element to remove")
removeElem = self.top.data
self.top = self.top.next
print(removeElem)
return removeElem
def peek(self):
"""
Display the topmost element in the stack
"""
if self.top is None:
raise Exception("The stack is empty. No element present")
print(self.top.data)
return self.top.data
def isEmpty(self):
"""
Return if the stack is empty or not
"""
if self.top is None:
return True
else:
return False
myStack = Stack()
myStack.push(3)
myStack.push(5)
myStack.push(-10)
print(myStack.pop())
def reverseString(myText):
"""
Reverse a string using the stack class
Input:
myText: String/text of any length
Returns:
reverseText : Reversed string
"""
textStack = Stack()
for textChar in myText:
textStack.push(textChar)
reverseText = ''
while not textStack.isEmpty():
reverseText += textStack.pop()
return reverseText
print(reverseString("We will conquere COVID-19"))
# In python, we can directly define stack using a list, collections.deque, queue.LifoQueue.
# We'll implement collections.deque below #
from collections import deque
class StackDeque:
def __init__(self):
self.container = deque()
def push(self, data):
self.container.append(data)
def pop(self):
return self.container.pop()
def peek(self):
return self.container[-1]
def isEmpty(self):
return len(self.container) == 0
def size(self):
return len(self.container)