A Level STACK: Reverse stack 反转stack

茅曾琪
2023-12-01
7. Write a program that reads in a sequence of characters and prints them
    in reverse order.  Use a stack.

STACK 定义,pop(),push()函数定义

stack = [None for index in range(0, 10)]
basePointer = 0
topPointer = -1
stackFull = 10
item = None


def pop():
    global topPointer, basePointer, item
    item = None
    if topPointer == basePointer - 1:
        print("Stack is empty,cannot pop")
    else:
        item = stack[topPointer]
        stack[topPointer] = None
        topPointer = topPointer - 1

    return item



def push(item):
    global topPointer
    if topPointer < stackFull - 1:
        topPointer = topPointer + 1
        stack[topPointer] = item
    else:
        print("Stack is full, cannot push")

Reverse函数定义

s = "Computer"

def reverse(s):
    returnString=""
    
    #先push s中的所有字符入栈
    for i in range(len(s)):
        push(s[i])
        
    #在把pop掉的字符都添加到returnString中
    for i in range(len(s)):
        returnString += pop()

    return returnString


print(reverse(s))

 类似资料: