完成下列程序,该程序实现栈的链式存储结构,构建链栈(栈中的元素依次为China,Japan,France,India,Australia),依次进行进栈和出栈操作,判断栈空和栈满操作,返回栈顶元素操作。要求生成链栈时,从键盘上读取数据元素
时间: 2024-03-17 15:44:27 浏览: 22
```c++
#include <iostream>
using namespace std;
// 定义链栈结构体
struct ListNode {
string data;
ListNode* next;
};
// 初始化链栈
void initStack(ListNode*& top) {
top = NULL;
}
// 判断栈空
bool isEmpty(ListNode* top) {
return top == NULL;
}
// 进栈
bool push(ListNode*& top, string data) {
ListNode* newNode = new ListNode;
newNode->data = data;
newNode->next = top;
top = newNode;
return true;
}
// 出栈
bool pop(ListNode*& top) {
if (isEmpty(top)) {
return false;
}
ListNode* temp = top;
top = top->next;
delete temp;
return true;
}
// 返回栈顶元素
string getTop(ListNode* top) {
if (isEmpty(top)) {
return "";
}
return top->data;
}
// 测试
int main() {
ListNode* top;
initStack(top);
string countries[] = {"China", "Japan", "France", "India", "Australia"};
for (int i = 0; i < 5; i++) {
push(top, countries[i]);
}
cout << "栈顶元素是:" << getTop(top) << endl;
cout << "依次出栈的元素是:";
while (!isEmpty(top)) {
cout << getTop(top) << " ";
pop(top);
}
cout << endl;
return 0;
}
```