c链栈

#include <iostream>
#include <malloc.h>
using namespace std;
typedef struct linkNode {
	char data;
	struct linkNode* next;
}linkStNode;
//初始化栈
void InitStack(linkStNode*& s) {
	s = (linkStNode*)malloc(sizeof(linkStNode));
	s->next = NULL;
}
//判断栈是否为空
bool EmptyStack(linkStNode* s) {
	return (s->next == NULL);
}
//进栈
bool PushStack(linkStNode*& s, char c) {
	linkStNode* n = (linkStNode*)malloc(sizeof(linkStNode));
	n->data = c;
	n->next = s->next;
	s->next = n;
	return true;
}
//出栈
bool PopStack(linkStNode*& s, char& c) {
	linkStNode* p = NULL;
	if (s->next == NULL)
	{
		return false;
	}
	else {
		p = s->next;
		c = p->data;
		s->next = p->next;
		free(p);
		return true;
	}
}
//销毁栈
void DestroyStack(linkStNode*& s) {
	linkStNode* pre = s, * p = s->next;
	while (p != NULL)
	{
		free(pre);
		pre = p;
		p = pre->next;
	}
	free(pre);
}

int main() {
	linkStNode* S = NULL;
	char n = '\0';
	InitStack(S);
	cout << (EmptyStack(S) ? "空" : "非空") << endl;
	cout << "将a,b,c,d,e按顺序依次进栈" << endl;
	PushStack(S, 'a');
	PushStack(S, 'b');
	PushStack(S, 'c');
	PushStack(S, 'd');
	PushStack(S, 'e');
	cout << (EmptyStack(S) ? "空" : "非空") << endl;
	while (!EmptyStack(S)) {
		PopStack(S, n);
		cout << n << endl;
	}
	cout << (EmptyStack(S) ? "空" : "非空") << endl;
	DestroyStack(S);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值