数据结构与算法 实验3 栈、队列和递归的基本操作

1. 实验目的

考察能否正确理解栈的顺序存储结构,以及对顺序栈基本操作的掌握程度。

2. 实验介绍

 掌握栈和队列的特点,并能在相应的应用问题中正确选用。熟练掌握栈的顺序栈和链栈的进栈出栈算法,特别应注意栈满和栈空的条件。掌握利用栈实现表达式求值的算法,了解迷宫求解算法。理解递归算法执行过程中栈的状态变化过程,了解将递归程序转换为非递归程序的方法。熟练掌握循环队列和链队列的进队出队算法,特别是循环队列中队头与队尾指针的变化情况。

3.实验内容

 创建名为 ex030501_01.py 的文件,在其中编写一个顺序栈的类,该类必须包含顺序栈

的定义及基本操作,并通过以下步骤测试基本操作的实现是否正确。

(1)初始化一个顺序栈 SequenceStack。 (2)判断栈是否为空。

(3)将元素 1,3,5 依次进栈。 (4)遍历栈内所有元素。 (5)获取栈顶元素。

(6)获取栈的长度。

(7)将栈中元素依次出栈并输出。

(8)判断栈是否为空。

4. 实验步骤与代码

class SequenceStack():
    def __init__(self):
        self.Max=10
        self.s=[None for i in range(0,self.Max)]
        self.top=-1

    def Create(self):
        if self.top>=self.Max-1:
            print("栈满")
            return
        print("输入'#'退出")
        Element=input("请输入元素:")
        while Element !='#':
            if self.top>=self.Max-1:
                print("栈满")
                return
            self.top+=1
            self.s[self.top]=Element
            Element=input("请输入元素:")

    def IsEmpty(self):
        if self.top==-1:
            return True
        else:
            return False

    def ForStack(self):
        if self.IsEmpty():
            print("栈为空")
            return
        for i in range(0,self.top+1):
            print(self.s[i])

    def GetTop(self):
        if self.IsEmpty():
            print("栈为空")
            return
        print("栈顶元素:",self.s[self.top])

    def GetLength(self):
        if self.IsEmpty():
            print("栈为空")
            return
        print("栈的长度:",self.top+1)

    def PopStack(self):
        if self.IsEmpty():
            print("栈为空")
            return
        while self.top>-1:
            print(self.s[self.top],"出栈")
            self.top-=1

s=SequenceStack()
if s.IsEmpty():
    print("栈为空")
else:
    print("栈不为空")
s.Create()
s.ForStack()
s.GetTop()
s.GetLength()
s.PopStack()
if s.IsEmpty():
    print("栈为空")
else:
print("栈不为空")

5.实验结果

猜你喜欢

转载自blog.csdn.net/qq_58664081/article/details/121373415