【无标题】第三章---链栈

链栈的初始化,入栈,出栈。(带头结点)

#include <iostream>
using namespace std;

struct LiStack{
	int data;
	LiStack *next;
};

void InitStack(LiStack *&L){
	int x;
	cin>>x;
	L->next=NULL;
	while(x!=9999){
		LiStack *p;
		p=new LiStack;
		p->data=x;
		p->next=L->next;
		L->next=p;
		cin>>x;
	}
}//初始化栈 

bool Push(LiStack *&L,int x){
	LiStack *p;
	p=new LiStack;
	p->data=x;
	p->next=L->next;
	L->next=p;
}//入栈

bool Pop(LiStack *&L,int &x){
	if(L->next==NULL)
		return false;
	LiStack *p;
	p=L->next;
	x=p->data;
	L->next=p->next;	
	delete p;
	return true;
}//出栈 

int main(void){
	LiStack *L;
	L=new LiStack;
	InitStack(L);
	int x;
	cout<<"请输入入栈元素:"<<endl;
	cin>>x;
	if(Push(L,x))
		cout<<x<<"已入栈"<<endl; 
	if(Pop(L,x)){
		cout<<x<<"已出栈"<<endl;
	}
	if(Pop(L,x)){
		cout<<x<<"已出栈"<<endl;
	}
}

不带头结点(推荐)

#include <iostream>
using namespace std;

struct LiStack{
	int data;
	LiStack *next;
};

void InitStack(LiStack *&top){
	int x;
	cin>>x;
	top->data=x;
	top->next=NULL;
	while(x!=9999){
		LiStack *p;
		p=new LiStack;
		p->data=x;
		p->next=top;
		top=p;
		cin>>x;
	}
}//初始化栈(不带头结点) 

bool Push(LiStack *&top,int x){
	LiStack *p;
	p=new LiStack;
	p->data=x;
	p->next=top;
	top=p;
}//入栈(不带头结点)

bool Pop(LiStack *&top,int &x){
	if(top==NULL)
		return false;
	LiStack *p;
	p=top;
	x=p->data;
	top=top->next;	
	delete p;
	return true;
}//出栈 

int main(void){
	LiStack *top;
	top=new LiStack;
	InitStack(top);
	int x=10;
	cout<<"请输入入栈元素:"<<endl;
	cin>>x;
	if(Push(top,x))
		cout<<x<<"已入栈"<<endl; 
	if(Pop(top,x)){
		cout<<x<<"已出栈"<<endl;
	}
	if(Pop(top,x)){
		cout<<x<<"已出栈"<<endl;
	}
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值