顺序栈或链栈的建立入栈出栈代码
时间: 2024-10-09 11:02:25 浏览: 28
C#实现顺序栈和链栈的代码实例
5星 · 资源好评率100%
顺序栈(基于数组实现):
```cpp
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
int stack[MAX_SIZE];
int top = -1; // 栈顶指针
// 函数用于判断栈是否已满
bool isFull() {
return (top == MAX_SIZE - 1);
}
// 函数用于判断栈是否为空
bool isEmpty() {
return (top == -1);
}
// 入栈操作
void push(int item) {
if (!isFull()) {
top++;
stack[top] = item;
cout << "元素 " << item << " 入栈成功" << endl;
} else {
cout << "栈已满,无法入栈" << endl;
}
}
// 出栈操作
int pop() {
if (!isEmpty()) {
int item = stack[top];
top--;
cout << "元素 " << item << " 出栈成功" << endl;
return item;
} else {
cout << "栈为空,无法出栈" << endl;
return -1; // 返回特殊值表示栈空
}
}
int main() {
while (true) {
cout << "选择操作:1. 入栈 2. 出栈 3. 查看栈顶 4. 退出" << endl;
int choice;
cin >> choice;
switch (choice) {
case 1:
int item;
cout << "请输入入栈元素:" << endl;
cin >> item;
push(item);
break;
case 2:
int popped = pop();
if (popped != -1)
cout << "刚出栈的元素是:" << popped << endl;
break;
// ...其他选项...
default:
cout << "无效的选择,程序结束" << endl;
break;
}
}
return 0;
}
```
链栈(基于链表实现):
```cpp
#include <iostream>
struct Node {
int data;
Node* next;
};
class Stack {
private:
Node* top;
public:
Stack() { top = nullptr; }
void push(int item) {
Node* newNode = new Node{item, top};
top = newNode;
cout << "元素 " << item << " 入栈成功" << endl;
}
int pop() {
if (top != nullptr) {
int item = top->data;
Node* temp = top;
top = top->next;
delete temp;
cout << "元素 " << item << " 出栈成功" << endl;
return item;
} else {
cout << "栈为空,无法出栈" << endl;
return -1;
}
}
// ...其他相关操作...
};
int main() {
Stack s;
// ...继续使用链栈进行操作...
}
```
阅读全文