#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
typedef struct node
{
int data;
struct node*next;
}Node;
typedef struct stack
{
Node *top;
int count;
}Stack;
Stack *push_stack(stack *s,int data)
{
if(s==NULL)
{
cout<<"该栈未创建!"<<endl;
return NULL;
}
Node *t;
t=(Node*)malloc(sizeof(Node));
t->data=data;
t->next=s->top;
s->top=t;
s->count++;
return s;
}
Stack *pop_stack(stack *s)
{
Node *t;
t=s->top;
if(s->top==NULL)
{
cout<<"ERROR STACK EMPTY!"<<endl;
return s;
}
else
{
s->top=s->top->next;
free(t);
s->count--;
return s;
}
}
int display_stack(stack *s)
{
Node *tp;
tp=s->top;
if(s->top==NULL)
{
cout<<"ERROR STACK EMPTY!"<<endl;
return 0;
}
int pos=1;
while(tp!=NULL)
{
cout<<"第"<<pos++<<"个元素的值为:"<<tp->data<<endl;
tp=tp->next;
}
cout<<endl;
return 0;
}
int main()
{
//初始化栈
Stack *s=(Stack*)malloc(sizeof(Stack));
s->top=NULL;
s->count=0;
//测试push操作
cout<<"*******************************"<<endl;
s=push_stack(s,10);
s=push_stack(s,20);
s=push_stack(s,30);
cout<<"当前栈的数据如下所示:"<<endl;
display_stack(s);
cout<<"*******************************"<<endl;
cout<<"执行一次POP操作之后如下所示:"<<endl;
s=pop_stack(s);
display_stack(s);
cout<<"*******************************"<<endl;
cout<<"所有操作执行完毕!"<<endl;
cout<<"*******************************"<<endl;
return 0;
}
链栈的基本操作
最新推荐文章于 2025-05-09 22:36:54 发布