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);
}
运行结果:
总结:学会运用链表的方式建栈,熟悉步骤