php网站空间支持,有域名和服务器怎么建网站,视频制作费用收费标准,做网站app要注册哪类商标C实现顺序栈类的定义#xff0c;编写main ()函数验证顺序栈类设计的合理性
以下是一个简单的C代码示例#xff0c;用于实现顺序栈类的定义并编写main()函数来验证其合理性#xff1a;
#include iostream
using namespace std;const int MAX_SIZE 100; // 定义栈的…C实现顺序栈类的定义编写main ()函数验证顺序栈类设计的合理性
以下是一个简单的C代码示例用于实现顺序栈类的定义并编写main()函数来验证其合理性
#include iostream
using namespace std;const int MAX_SIZE 100; // 定义栈的最大容量class SeqStack {
private:int top; // 栈顶指针int data[MAX_SIZE]; // 存储栈元素的数组
public:SeqStack() { // 构造函数初始化栈顶指针top -1;}bool isEmpty() { // 判断栈是否为空return top -1;}bool isFull() { // 判断栈是否已满return top MAX_SIZE - 1;}void push(int item) { // 元素入栈if (isFull()) {cout Stack is full. Cannot push element. endl;} else {data[top] item;}}int pop() { // 元素出栈if (isEmpty()) {cout Stack is empty. Cannot pop element. endl;return -1;} else {return data[top--];}}int peek() { // 返回栈顶元素if (isEmpty()) {cout Stack is empty. No element to peek. endl;return -1;} else {return data[top];}}
};int main() {SeqStack stack;// 验证顺序栈类的设计stack.push(10);stack.push(20);stack.push(30);cout Peek: stack.peek() endl;cout Pop: stack.pop() endl;cout Pop: stack.pop() endl;cout Pop: stack.pop() endl;cout Is empty? (stack.isEmpty() ? Yes : No) endl;return 0;
}
这段代码实现了一个顺序栈类SeqStack其中包含了常用的栈操作函数如入栈push、出栈pop、判断栈是否为空isEmpty以及返回栈顶元素peek等。在main()函数中我们对顺序栈类进行了简单的测试和验证。