tt
unknown
python
2 years ago
2.3 kB
36
Indexable
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, data):
node = Node(data)
node.next = self.top
self.top = node
def pop(self):
popped_data = self.top.data
self.top = self.top.next
return popped_data
def peek(self):
if self.top is None:
return None
else:
return self.top.data
def max(self):
current = self.top
max = self.top.data
while current:
if max > current.data:
max = max
else:
max = current.data
current = current.next
print('Max value: ', max)
def size(self):
current = self.top
size = 0
while current:
size+=1
current = current.next
print('Size: ', size)
def is_palindrome(self, str):
for i in str:
self.push(i)
for i in str:
if i == self.peek():
self.pop()
else:
self.pop()
return False
return True
def reverse(self):
if self.top is None:
print('Stack is empty')
return
# Create a copy of the original stack
original_stack = Stack()
current = self.top
while current:
original_stack.push(current.data)
current = current.next
# Move elements from the original stack to the auxiliary stack
aux_stack = Stack()
while original_stack.top:
aux_stack.push(original_stack.pop())
# Move elements back from the auxiliary stack to the original stack
while aux_stack.top:
self.push(aux_stack.pop())
def display(self):
current = self.top
while current:
print(current.data, '', end='')
current = current.next
stack = Stack()
stack.push(10)
stack.push(5)
stack.push(2)
stack.push(3)
stack.push(7)
stack.max()
stack.size()
stack.display()
stack.reverse()
print()
stack.display()Editor is loading...
Leave a Comment