栈——链表实现

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
#define ms(a) memset(a,0,sizeof(a))
#define N 30
//栈 需要一个表头 
typedef int Elementtype;

struct node{
	Elementtype Element;
	node* next=NULL;
};

typedef node* STACK;
typedef node* ptrnode;

//判断栈是否为空,空返回 1;
int IsEmpty(STACK S){
	return S->next==NULL;
} 

// 压栈
void Push(Elementtype x,STACK &S){
	ptrnode tem=new node;
	tem->Element=x;
	tem->next=S->next;
	S->next=tem;
} 

// 返回栈顶元素
Elementtype Top(STACK S){
	if(IsEmpty(S)){
		cout<<"The stack is empty."<<endl; 
	}
	else{
		return S->next->Element;
	}
} 

// 出栈
void Pop(STACK &S){
	ptrnode tem;
	if(IsEmpty(S)){
		cout<<"The stack is empty."<<endl;
		return ;
	}
	tem=S->next;
	S->next=tem->next;
	delete(tem);
	
} 

//置空栈
void MakeEmpty(STACK S){
	while(!IsEmpty(S)){
		Pop(S);
	}
} 

//创建一个栈
STACK CreateStack(){
	STACK S;
	S=new node;
	MakeEmpty(S);
	return S;
} 

//打印栈中所有元素
void Print(STACK S){
	if(IsEmpty(S)){
		cout<<"The stack is empty."<<endl;
		return ;
	}
	ptrnode tem=S->next;
	while(tem!=NULL){
		cout<<tem->Element<<" ";
		tem=tem->next;
	}
	cout<<endl;
} 

int main(){
	STACK S=CreateStack();
	Push(5,S);
	Push(4,S);
	Push(3,S);
	Push(2,S);
	Push(1,S);
	Print(S);
	cout<<Top(S)<<endl;
	Pop(S);
	Print(S);
	Pop(S);
	Print(S);
	Pop(S);
	Print(S);
	cout<<Top(S)<<endl;
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值