使用链栈编写程序,依次进栈数据为 1,2,3,4,5,再全部出栈,输出出栈序列
时间: 2023-08-18 21:03:53 浏览: 92
栈的顺序实现,入栈、出栈等
以下是使用链栈编写的程序,实现依次进栈数据为1,2,3,4,5,再全部出栈的操作,并输出出栈序列:
```C++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedStack {
private:
Node* top;
public:
LinkedStack() {
top = nullptr;
}
~LinkedStack() {
while (!isEmpty()) {
pop();
}
}
void push(int val) {
Node* newNode = new Node;
newNode->data = val;
newNode->next = top;
top = newNode;
}
bool isEmpty() {
return top == nullptr;
}
int pop() {
if (isEmpty()) {
cout << "Stack is empty!" << endl;
exit(1);
}
Node* temp = top;
int val = temp->data;
top = temp->next;
delete temp;
return val;
}
};
int main() {
LinkedStack stack;
for (int i = 1; i <= 5; i++) {
stack.push(i);
}
cout << "出栈序列:";
while (!stack.isEmpty()) {
cout << stack.pop() << " ";
}
return 0;
}
```
程序运行结果为:
```
出栈序列:5 4 3 2 1
```
阅读全文