forked from TARANG0503/DSA-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Delete middle element of a stack
65 lines (49 loc) · 1.13 KB
/
Delete middle element of a stack
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
# Python3 code to delete middle of a stack
# without using additional data structure.
# Deletes middle of stack of size
# n. Curr is current item number
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def deleteMid(st, n, curr) :
# If stack is empty or all items
# are traversed
if (st.isEmpty() or curr == n) :
return
# Remove current item
x = st.peek()
st.pop()
# Remove other items
deleteMid(st, n, curr+1)
# Put all items back except middle
if (curr != int(n/2)) :
st.push(x)
# Driver function to test above functions
st = Stack()
# push elements into the stack
st.push('1')
st.push('2')
st.push('3')
st.push('4')
st.push('5')
st.push('6')
st.push('7')
deleteMid(st, st.size(), 0)
# Printing stack after deletion
# of middle.
while (st.isEmpty() == False) :
p = st.peek()
st.pop()
print (str(p) + " ", end="")
# This code is contributed by
# Manish Shaw (manishshaw1)