#include<iostream>
using namespace std;
typedef struct Node *PtrToNode;
typedef struct Node *Stack; //typedef PtrToNode Stack
struct Node
{
int n;
struct Node *next;
};
//创建
Stack creat_stack()
{
Stack s;
s = new struct Node;
if (s == NULL) {
cout << "Out of space" << endl;
return 0;
}
s->next = NULL;
return s;
}
//进栈
void push(int x, Stack s)
{
PtrToNode temp;
temp = new struct Node;
if (temp == NULL) {
cout << "Out of space!" << endl;
return;
}
temp->n = x;
temp->next = s->next;
s->next = temp;
}
//判断是否空栈
int IsEmpty(Stack s)
{
return s->next == NULL;
}
//返回栈顶元素
int top(Stack s)
{
if (IsEmpty(s)) {
cout << "Empty stack!" << endl;
return 0;
}
return s->next->n;
}
//出栈
void pop(Stack s)
{
PtrToNode temp=s->next;
if (IsEmpty(s)) {
cout << "Empty stack!" << endl;
return;
}
cout << "执行出栈!" << endl;
s->next = temp->next;
free(temp);
}
//遍历输出
void display(Stack s)
{
PtrToNode tmp;
tmp = s->next;
cout << "遍历栈:";
while (tmp!= NULL) {
cout << tmp->n << " ";
tmp = tmp->next;
}
cout << endl;
}
int main()
{
Stack s;
s = creat_stack();
push(4, s);
push(10, s);
push(5, s);
push(7, s);
display(s);
cout << "栈顶元素:" << top(s) << endl;
pop(s);
display(s);
}
栈的链表实现
最新推荐文章于 2022-10-03 16:54:25 发布