Skip to content

Commit 509ff30

Browse files
authored
Create Stack Reversal
1 parent 03a4251 commit 509ff30

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

data_structures/stacks/Stack Reversal

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class Stack:
2+
def __init__(self):
3+
self.items = []
4+
5+
def push(self, item):
6+
self.items.append(item)
7+
8+
def pop(self):
9+
if not self.is_empty():
10+
return self.items.pop()
11+
return None
12+
13+
def is_empty(self):
14+
return len(self.items) == 0
15+
16+
def peek(self):
17+
if not self.is_empty():
18+
return self.items[-1]
19+
return None
20+
21+
def size(self):
22+
return len(self.items)
23+
24+
def reverse(self):
25+
if not self.is_empty():
26+
# Remove the top element
27+
top = self.pop()
28+
# Reverse the remaining stack
29+
self.reverse()
30+
# Insert the removed element at the bottom
31+
self.insert_at_bottom(top)
32+
33+
def insert_at_bottom(self, item):
34+
if self.is_empty():
35+
self.push(item)
36+
else:
37+
# Remove all items
38+
top = self.pop()
39+
# Insert item at the bottom
40+
self.insert_at_bottom(item)
41+
# Put the removed items back
42+
self.push(top)
43+
44+
def __str__(self):
45+
return str(self.items)
46+
47+
# Example usage
48+
stack = Stack()
49+
stack.push(1)
50+
stack.push(2)
51+
stack.push(3)
52+
stack.push(4)
53+
54+
print("Original stack:", stack)
55+
stack.reverse()
56+
print("Reversed stack:", stack)

0 commit comments

Comments
 (0)