Skip to content

Commit 6c3b274

Browse files
committed
Python implementation of Stack
1 parent 325deda commit 6c3b274

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

data_structures/Stacks/Stack.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Author: OMKAR PATHAK
2+
3+
class Stack(object):
4+
def __init__(self, limit = 10):
5+
self.stack = []
6+
self.limit = limit
7+
8+
# for printing the stack contents
9+
def __str__(self):
10+
return ' '.join([str(i) for i in self.stack])
11+
12+
# for pushing an element on to the stack
13+
def push(self, data):
14+
if len(self.stack) >= self.limit:
15+
print('Stack Overflow')
16+
else:
17+
self.stack.append(data)
18+
19+
# for popping the uppermost element
20+
def pop(self):
21+
if len(self.stack) <= 0:
22+
return -1
23+
else:
24+
return self.stack.pop()
25+
26+
# for peeking the top-most element of the stack
27+
def peek(self):
28+
if len(self.stack) <= 0:
29+
return -1
30+
else:
31+
return self.stack[len(self.stack) - 1]
32+
33+
# to check if stack is empty
34+
def isEmpty(self):
35+
return self.stack == []
36+
37+
# for checking the size of stack
38+
def size(self):
39+
return len(self.stack)
40+
41+
if __name__ == '__main__':
42+
myStack = Stack()
43+
for i in range(10):
44+
myStack.push(i)
45+
print(myStack)
46+
myStack.pop() # popping the top element
47+
print(myStack)
48+
myStack.peek() # printing the top element
49+
myStack.isEmpty()
50+
myStack.size()

0 commit comments

Comments
 (0)