-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07_sort_stack.py
More file actions
57 lines (39 loc) · 1.45 KB
/
Copy path07_sort_stack.py
File metadata and controls
57 lines (39 loc) · 1.45 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
from collections import deque
class Stack:
def __init__(self):
self.container = deque()
def push(self, val):
self.container.append(val)
def peek(self):
return self.container[-1]
def pop(self):
return self.container.pop()
def size(self):
return len(self.container)
def display(self):
return self.container
stack1 = Stack() # main stack
stack2 = Stack() #stack to store elements temporarily
numbers = int(input("Enter no. of elements to store in stack : "))
for i in range(numbers):
element = int(input("Enter element to store in stack : "))
# if element is greater than push directly
if stack1.size() > 0 and element > stack1.peek():
stack1.push(element)
print(stack1.display())
# if element is small than the top element of stack1
elif stack1.size() > 0 and element < stack1.peek():
# first pop and push those elements to stack2
while(stack1.size() > 0 and stack1.peek() > element):
stack2.push(stack1.pop())
stack1.push(element)
print(stack1.display())
# again pushing the elements of stack2 to stack1
while(stack2.size() > 0):
stack1.push(stack2.pop())
print(stack1.display())
# condition to push the first element in the stack
elif stack1.size() == 0:
stack1.push(element)
print(stack1.display())
print(stack1.display())