-
Notifications
You must be signed in to change notification settings - Fork 43
/
stack.py
94 lines (79 loc) · 2.54 KB
/
stack.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
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
#---------------------------------------------------------------
# STACK
#---------------------------------------------------------------
# V0
class Stack(object):
def __init__(self, limit = 10):
self.stack = []
self.limit = limit
# for printing the stack contents
def __str__(self):
return ' '.join([str(i) for i in self.stack])
# for pushing an element on to the stack
def push(self, data):
if len(self.stack) >= self.limit:
print('Stack Overflow')
else:
self.stack.append(data)
# for popping the uppermost element
def pop(self):
if len(self.stack) <= 0:
return -1
else:
return self.stack.pop()
# for peeking the top-most element of the stack
def peek(self):
if len(self.stack) <= 0:
return -1
else:
return self.stack[len(self.stack) - 1]
# to check if stack is empty
def isEmpty(self):
return self.stack == []
# for checking the size of stack
def size(self):
return len(self.stack)
# V1
# https://github.com/OmkarPathak/Data-Structures-using-Python/blob/master/Stack/Stack.py
class Stack(object):
def __init__(self, limit = 10):
self.stack = []
self.limit = limit
# for printing the stack contents
def __str__(self):
return ' '.join([str(i) for i in self.stack])
# for pushing an element on to the stack
def push(self, data):
if len(self.stack) >= self.limit:
print('Stack Overflow')
else:
self.stack.append(data)
# for popping the uppermost element
def pop(self):
if len(self.stack) <= 0:
return -1
else:
return self.stack.pop()
# for peeking the top-most element of the stack
def peek(self):
if len(self.stack) <= 0:
return -1
else:
return self.stack[len(self.stack) - 1]
# to check if stack is empty
def isEmpty(self):
return self.stack == []
# for checking the size of stack
def size(self):
return len(self.stack)
# if __name__ == '__main__':
# myStack = Stack()
# for i in range(10):
# myStack.push(i)
# print(myStack) # show all elements in the Stack (method 1 )
# myStack.pop() # popping the top element
# print(myStack)
# myStack.peek() # printing the top element
# myStack.isEmpty()
# myStack.size()
# myStack.__str__() # show all elements in the Stack (method 2 )