链栈的基本操作

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温柔济沧海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值