-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathStackImple.py
More file actions
48 lines (44 loc) · 1.18 KB
/
StackImple.py
File metadata and controls
48 lines (44 loc) · 1.18 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
# Stack class implementation
# Author: Pradeep K. Pant, https://pradeeppant.com
# Implement basic operation in stack
# Stack follows LIFO sequence
# Initialize Stack class and set a empty list
class Stack(object):
def __init__(self):
self.items=[]
# Check if list is empty
def isEmpty(self):
return self.items == []
# Push an element in a stack
def push(self,item):
self.items.append(item)
# POP an element from top of the stack
def pop(self):
return self.items.pop()
# Just peek into top element of the stack (don't perform any operation)
def peek(self):
return self.items[len(self.items)-1]
# Check size of a stack (how may elements are stored)
def size(self):
return len(self.items)
# Test
# Create an object and try basic operation
sObj = Stack()
# Check if list is empty
print (sObj.isEmpty())
# Add an element
sObj.push(1)
# Add another element
sObj.push(2)
# Peek into stack and check top element
print (sObj.peek())
# Check again if empty
print (sObj.isEmpty())
# Check size
print (sObj.size())
# show items
print (sObj.items)
# Remove item (First-In-First-Out)
print (sObj.pop())
# Check again items
print (sObj.items)