栈--链表形式

栈--链表形式

实现下列操作。
1.初始化空栈。
2. 键盘输入字符,使得输入的字符依次入栈(结束符号自定,例如回车键(值为10)或'#') 
每插入一个元素,必须输出当时的栈顶元素(调用GetLinkStackTop函数)。 
3.判断链栈是否为空。输出判断结果。
4.调用出栈函数,打印出栈元素的值;反复此步骤,直至栈为空。
5.判断链栈是否为空。输出判断结果。
6.释放链栈。

#include <iostream>
#include <string.h>
using namespace std;

typedef char ElemType;                   

typedef struct linknode{
	ElemType data;
	struct linknode *next;
}LiStack;

void InitStack(LiStack * &s){            //initialize a LiStack
	s = new LiStack;
	s->next = NULL; 
}

void Push(LiStack *&s,ElemType e){    //add the data to LiStack
	LiStack *p;
	p = new LiStack;
	p->data=e;
	p->next = s->next;
	s->next=p;
}

bool Pop(LiStack * &s,ElemType &e){      //delete the data which is in the top 
	LiStack *p;
	if(s->next==NULL)
		return false;
	p=s->next;
	e=p->data;
	s->next=p->next;
	delete(p);
	return true;
}

bool StackEmpty(LiStack * &s){           //judge the LiStack is empty or not 
	return (s->next==NULL);
}

bool GetTop(LiStack * &s,ElemType &e){   //get the data which is in the top 
	if(s->next==NULL)
		return false;
	e=s->next->data;
	return false;
}
  
void DestroyStack(LiStack * &s){         //destroy the LiStack 
	LiStack *p =s ,*q=s->next;
	while(q!=NULL){
		delete(p);
		p = q;
		q = p->next;
	}
	delete(p);
}

int main(){
	char c[100],ch;
	ElemType e;
	LiStack *s;
	
	InitStack(s);                         //initialize the LiStack
	
	int i=0;
	while((ch=getchar())!='\n'){          //add the data to the LiStack and print the data in the top 
		if(ch!=' ')
			c[i]=ch;
		else continue;
		Push(s,c[i]);
		GetTop(s,e);
		cout<<"after add the top data is:\t"<<e<<endl;
		i++;
	}
	
	if(StackEmpty(s))                     //judge the LiStack is empty or not 
		cout<<endl<<endl<<"the LiStack is empty"<<endl; 
	else cout<<endl<<endl<<"the LiStack is not empty"<<endl<<endl<<endl;
	
	int j=1;                              //datele the top data and print it 
	while(s->next!=NULL){
		Pop(s,e);
		cout<<"the data "<<j<<" is:\t"<<e<<endl;;
		j++; 
	}
	
	if(StackEmpty(s))                     //judge the LiStack is empty or not 
		cout<<endl<<endl<<"the LiStack is empty"<<endl<<endl<<endl; 
	else cout<<endl<<endl<<"the LiStack is not empty"<<endl<<endl<<endl;
	
	DestroyStack(s);                      //destroy the LiStack
	
	cout<<"the LiStack has been Destroy"<<endl;
	
	return 0;
		
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

【ACGO】我不会C++

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

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

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

打赏作者

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

抵扣说明:

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

余额充值