栈是限定仅在表尾进行插入或者删除的操作受限的线性表;表头端称为栈底,表尾端称为栈顶。
链栈判空:S->next=NULL;
链栈判不存在:S=NULL;
#include "stdafx.h"
#include "iostream"
using namespace std;
typedef int ElemType;
typedef int Status;
typedef struct SNode {
ElemType data;
struct SNode *next;
}SNode, *LinkedStack;
//初始化栈
Status initLinkedStack(LinkedStack &S) { //链式栈结构无头节点
S = new SNode;
if (!S)
{
cout << "内存分配失败!" << endl;
return false;
}
S->next = NULL;
return true;
}
//向栈中插入元素
Status push(LinkedStack &S, int e) {
LinkedStack p;
p = new SNode; //新建节点
if (!p)
{
cout << "内存分配失败!" << endl;
return false;
}
p->data = e;
p->next = S->next; //将元素插入栈顶
S->next = p;
return true;
}
//判断某个节点是否为空
Status isEmpty(LinkedStack &S) {
if (S == NULL)
{
cout << "栈不存在!" << endl;
exit(0);
}
if (S->next == NULL)
return true;
else
return false;
}
//输出函数
Status visit(ElemType e) {
cout << e << " ";
return true;
}
//遍历链式栈
Status stackTraverse(LinkedStack &S) {
if (isEmpty(S))
{
cout << "链表为空!" << endl;
exit(0);
}
LinkedStack p;
p = S->next;
while (p)
{
visit(p->data);
p = p->next;
}
cout << endl;
return true;
}
//求长
Status getLength(LinkedStack &S) {
ElemType length = 0;
LinkedStack p;
p = S->next;
while (p)
{
++length;
p = p->next;
}
return length;
}
//获取栈顶元素
Status getTop(LinkedStack &S) {
return S->next->data;
}
//出栈,并返回出栈元素的值
Status pop(LinkedStack &S) {
int e;
if (isEmpty(S))
{
cout << "链栈为空!" << endl;
exit(0);
}
LinkedStack p;
p = S->next;
e = p->data;
S->next = p->next;
delete p;
return e;
}
//清空链栈
Status clearStack(LinkedStack &S) {
while (!isEmpty(S)) {
pop(S);
}
return true;
}
//销毁栈
Status destroyStack(LinkedStack &S) {
while (!isEmpty(S))
{
pop(S);
}
delete S;
S = NULL;
return true;
}
int main()
{
ElemType e;
LinkedStack stack;
cout << "初始化链栈" << endl;
initLinkedStack(stack);
cout << "请输入第一个元素:";
cin >> e;
push(stack, e);
cout << "请输入第二个元素:";
cin >> e;
push(stack, e);
cout << "请输入第三个元素:";
cin >> e;
push(stack, e);
cout << "该链栈为:";
stackTraverse(stack);
cout << "链表长度为:";
cout << getLength(stack) << endl;
cout << "栈顶元素为:" << getTop(stack) << endl;
cout << "执行一次出栈操作,出栈元素为:" << pop(stack) << endl;
cout << "执行清栈操作" << endl;
clearStack(stack);
stackTraverse(stack);
cout << "执行毁栈操作" << endl;
destroyStack(stack);
isEmpty(stack);
return 0;
}