#include <iostream>
using namespace std;
namespace linkstack {
typedef char DataType;
typedef struct Node{
DataType data;
Node *next;
}StackNode;
typedef StackNode *LinkStack;
LinkStack top;
void InitEmpty() {
top = nullptr;
}
bool StackEmpty() {
return top == nullptr;
}
void Push(DataType elem) {
StackNode *new_node = (StackNode*)malloc(sizeof(StackNode));
new_node->data = elem;
new_node->next = top;
top = new_node;
}
LinkStack Pop(DataType *elem) {
if (StackEmpty()) {
cout << "栈空" << endl;
exit(0);
}
LinkStack node = top;
*elem = top->data;
top = top->next;
free(node);
return top;
}
DataType GetTop() {
if (StackEmpty()) {
cout << "栈空" << endl;
exit(0);
}
return top->data;
}
}
int main() {
linkstack::InitEmpty();
linkstack::Push('5');
linkstack::Push('4');
linkstack::Push('3');
linkstack::Push('2');
linkstack::Push('1');
cout << "栈顶元素:" << linkstack::GetTop() << endl;
while (!linkstack::StackEmpty()) {
linkstack::DataType elem;
linkstack::Pop(&elem);
cout << "元素:" << elem << endl;
cout << "栈顶元素:" << linkstack::GetTop() << endl;
}
return 0;
}
链表栈实现
最新推荐文章于 2022-10-03 16:54:25 发布