第五周 项目 2 - 建立链栈算法库

sqstack.h  代码

/*
*Copyright (c) 2017,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:
*作    者:陈军正
*完成日期:2017年10月15日
*版 本 号:v1.0
*
* 
*/
typedef char ElemType;
typedef struct LinkNode
{
	ElemType data;
	struct LinkNode *next;
}LinkeStNode;
void InitStack(LinkeStNode *&s);  //初始化链表
bool StackEmpty(LinkeStNode *s);  //判断栈表是否为空
void Push(LinkeStNode *&s, ElemType e);  //入栈
int StackLength(LinkeStNode *&);   //栈的长度
void DispStack(LinkeStNode *&s);   //输出栈中的元素
bool Pop(LinkeStNode *&s, ElemType e);   //出栈
void DestroyStack(LinkeStNode *&s);   //摧毁栈表

main .cpp 代码

#include <iostream>
#include "list.h"
using namespace std;
int main()
{
	LinkeStNode *s;
	ElemType e=0;
	cout << "栈初始化" << endl;
	InitStack(s);
	cout << "栈是否为空:";
	if (StackEmpty(s))
		cout << "空" << endl;
	else
		cout << "非空" << endl;
	cout << "将a、b、c、d、e入栈";
	Push(s, 'a');
	Push(s, 'b');
	Push(s, 'c');
	Push(s, 'd');
	Push(s, 'e');
	cout << "栈是否为空:";
	if (StackEmpty(s))
		cout << "空" << endl;
	else 
		cout << "非空" << endl;
	cout << "栈的长度为:";
	cout << StackLength(s);
	cout << endl << "输出栈的元素:";
	DispStack(s);
	Pop(s, e);
	cout << e << endl;
	cout << "栈是否为空:";
	if (StackEmpty(s))
		cout << "空" << endl;
	else
		cout << "非空" << endl;
	DestroyStack(s);
	return 0;
}

list.cpp 代码

#include <iostream>
#include "list.h"
using namespace std;
void InitStack(LinkeStNode *&s)
{
	s = (LinkeStNode *)malloc(sizeof(LinkeStNode));
	s->next = NULL;
}
bool StackEmpty(LinkeStNode *s)
{
	return (s->next == NULL);
}
void Push(LinkeStNode *&s,ElemType e)
{
	LinkeStNode *p;
	p = (LinkeStNode *)malloc(sizeof(LinkeStNode));
	p->data = e;
	p->next = s->next;
	s->next = p;
}
int StackLength(LinkeStNode *&s)
{
	LinkeStNode *p = s->next;
	int n = 0;
	while (p != NULL)
	{
		p = p->next;
		n++;
	}
	return n;
}
void DispStack(LinkeStNode *&s)
{
	LinkeStNode *p = s->next;
	while (p != NULL)
	{
		cout << p->data << " ";
		p = p->next;
	}
}
bool Pop(LinkeStNode *&s, ElemType e)
{
	LinkeStNode *p;
	if (s->next == NULL)
		return false;
	p = s->next;
	e = p->data;
	s->next = p->next;
	free(p);
	return true;
}
void DestroyStack(LinkeStNode *&s)
{
	LinkeStNode *q = s,*p = s->next;
	while (p = NULL)
	{
		free(q);
		q = p;
		p = q->next;
	}
	free(q);
}
运行结果:

总结:学会运用链表的方式建栈,熟悉步骤

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值