堆栈的链式表示和实现

#include<iostream>
using namespace std;
typedef char DataType; //记得加分号

typedef struct snode
{
	DataType x;
	struct snode *next;
}SNode;

 void Initiate(SNode **head)
 {
	 (*head)=(SNode*)malloc(sizeof(SNode));
	 (*head)->next=NULL;
 }

 //入栈
 void StackPush(SNode *head,DataType x)
 {
	 if(head==NULL) 
	 {
		 cout<<"error"<<endl;
		 return ;
	 }
	 SNode *p;
	 p=(SNode*)malloc(sizeof(SNode));
	 p->x=x;
	 p->next=head->next;
	 head->next=p;
 }

 //出栈
 DataType StackPop(SNode *head)
 {
	 if(head->next==NULL)
	 {
		 cout<<"the stack is empty"<<endl;
		 return NULL;
	 }
	 SNode *p;
	 DataType d;
	 p=head->next;
	 d=p->x;
	 head->next=p->next;
	 free(p);
	 return d;	 
 }

 //取得栈顶元素
 DataType StackGet(SNode *head)
 {
	 if(head->next==NULL)
	 {
		 cout<<"the stack is empty"<<endl;
		 return NULL;
	 }
	 return head->next->x;
 }



 void Destroy(SNode *head)
 {
	 SNode *p,*p1;
	 p=head;
	 while(p->next!=NULL)
	 {
		 p1=p;
		 p=p->next;
		 free(p1);
	 }
 }

 int StackNotEmpty(SNode *head)
 {
	 if(head->next==NULL) return 0;
	 else return 1;
 }

 void main()
 {
	 SNode *stack;
	 Initiate(&stack);
	 StackPush(stack,'x');

	 cout<<StackGet(stack)<<endl;

	 StackPush(stack,'j');
	 StackPush(stack,'k');
	 cout<<StackPop(stack)<<endl;
	 cout<<StackPop(stack)<<endl;
	 cout<<StackPop(stack)<<endl;
	 cout<<StackPop(stack)<<endl;  //由于链式栈没有元素,所以输出空
	 if(StackNotEmpty(stack)) cout<<"Not empty"<<endl;
	 else cout<<"empty!"<<endl;
	 Destroy(stack);
	 system("pause");
 }





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值