- 实验目的
掌握栈数据结构的实现,验证各个栈的基本操作
二、实验环境(仪器设备、软件等)
机房计算机一台
Win10系统
Visual Studio 2022
三、实验原理(或要求)
本关要求针对“栈”这一数据结构完成六个操作函数,分别实现栈的初始化、进栈、出栈、判断栈是否为满、是否为空、求栈元素个数等功能。
具体要求如下:
(1)InitStack:初始化一个空栈
(2)Push:将元素x进栈,若满栈则无法进栈,返回false,否则返回true。
(3)Pop:若出栈成功(栈不为空),则返回true;否则(空栈),返回false。
(4)StackFull:判断栈是否为满,若栈为满,则返回true,否则返回false。
(5)StackEmpty:判断栈是否为空,若栈为空,则返回true,否则返回false。
(6)StackLength:获取栈元素个数。
样例输入:
6
push 56
push 15
push 12
push 13
pop
end
样例输出
Stack length: 3
stack data (from bottom to top): 56 15 12
四、实验步骤
- 打开 Visual Studio 2022 软件,在菜单中选择 “File” -> “New” -> “Project…”。
- 在弹出的对话框中选择 “Visual C++” -> “Empty Project”,并给项目命名,然后点击 “OK”。
- 在 “Solution Explorer” 中右键点击 “Header Files”,选择 “Add” -> “New Item…”,并创建一个名为 “Stack.h” 的头文件。
- 将下面的代码插入到 “FileName.h” 中。
#ifndef STACK_H
#define STACK_H
#include <vector>
class Stack {
private:
int capacity;
std::vector<int> data;
public:
Stack(int cap);
void initStack();
bool push(int x);
bool pop();
bool stackFull();
bool stackEmpty();
int stackLength();
};
#endif
- 在 “Solution Explorer” 中右键点击 “Source Files”,选择 “Add” -> “New Item…”,并创建一个名为 “Main.cpp” 的源文件。
- 将下面的代码插入到 “FileName.cpp” 中。
#include <iostream>
#include "Stack.h"
Stack::Stack(int cap) {
capacity = cap;
}
void Stack::initStack() {
data.clear();
}
bool Stack::push(int x) {
if (data.size() < capacity) {
data.push_back(