在python中使用push和pop将堆栈按降序排列


  • 接受来自用户的字符串并生成堆栈,直到获得输入"End">
  • 接下来,它应该以合适的顺序对给定的堆栈进行排序
  • 最后,打印排序后的堆栈

我似乎不能只使用push和pop方法得到正确的逻辑,其中push是一个将元素放在堆栈顶部的函数,而pop是一个删除堆栈顶部元素并存储它的函数。我只允许使用push和pop,排序算法是我唯一不能做的。

from Stack import Stack
def display_(S_):
node = S_.list.head
while node != None:
print(node.data)
node = node.next

def Sorting_Stack(stack,k):
v = 0
ar = 0
temp = Stack()
for i in range(k):
v = stack.pop()
temp.push(v)
node = stack.list.head
tnode = temp.list.head
if tnode.data > node.data:
ar = temp.pop()
stack.push(ar)

display_(stack)


if __name__ == '__main__':
stack = Stack()
string = ""
k = 0
while string!='End':
string = input()
if string == 'End':
break
else:
stack.push(string)
k += 1

Sorting_Stack(stack, k)

#this is Stack.py--------

from Node import Node
from LinkedList import LinkedList
class Stack:
def __init__(self):
self.list = LinkedList()

def push(self, new_item):
# Create a new node to hold the item
new_node = Node(new_item)

# Insert the node as the list head (top of stack)
self.list.prepend(new_node)

def pop(self):
# Copy data from list's head node (stack's top node)
popped_item = self.list.head.data

# Remove list head
self.list.remove_after(None)

# Return the popped item
return popped_item

#Stack class

class Stack:
def __init__(self):
self.stack = []
def push(self,item):
if item == 'End':
self.sort()
else:
self.stack.append(item)
def pop(self):
if len(self.stack) == 0:
print("Stack Is Empty")
else:
self.stack.pop()
def sort(self):
self.stack.sort()
print(self.stack)

给出输入

s = Stack()
item = None
while item !='End':
print("Type 'End' For Ending the Stack Push Operation")
item = input("Enter Item: ")
s.push(item)
s.push(item)

程序将接收输入,直到我们将输入作为'End'。在给定'End'作为输入后,它将对堆栈进行排序并打印它。

最新更新