#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct NODE
{
int data;
struct NODE *link;
}node, *pnode;
pnode creatStack(); //创建一个空栈
int isEmpty(pnode top); //判断是否为空栈
void cintStack(pnode top);//圧栈操作
void coutStack(pnode top);//出栈操作
void showStack(pnode top);//遍历栈
void setEmpty(pnode top); //把栈置空
void destoryStack(pnode top);//摧毁栈
int main()
{
pnode top;
top = creatStack();
cintStack(top);
showStack(top);
coutStack(top);
showStack(top);
setEmpty(top);
destoryStack(top);
return 0;
}
pnode creatStack()//创建一个空栈
{
pnode top = (pnode)malloc(sizeof(node));
if(top == NULL)
{
cout << "栈建立失败" << endl;
return 0;
}
else
{
top->link = NULL;
}
return top;
}
int isEmpty(pnode top)//判断是否为空栈
{
if(top->link == NULL)
{
return 0;
}
else
{
return 1;
}
}
void cintStack(pnode top)//进栈操作
{
cout << "****************进栈操作**************" << endl;
int data, n = 0, i = 1;
cout << "进栈的结点数目" << endl;
cin >> n;
while(n--)
{
pnode pnew = (pnode)malloc(sizeof(node));
if(pnew == NULL)
{
cout << "进栈失败" << endl;
return;
}
cout << "请输入第" << i <<"个进栈的数据" << endl;
cin >> data;
pnew->data = data;
pnew->link = top->link;
top->link = pnew;
i++;
}
cout << "进栈成功" << endl;
}
void coutStack(pnode top)//出栈操作
{
cout << "****************出栈操作**************" << endl;
if( !isEmpty(top) )
{
cout << "栈已空" << endl;
return;
}
else
{
pnode temp;
temp = top->link;
top->link = temp->link;
free(temp);
cout << "出栈成功" << endl ;
}
}
void showStack(pnode top)//展示栈的所以结点内容
{
cout << "****************遍历操作**************" << endl;
int i = 1;
pnode pt = top->link;
if(!isEmpty(top))
{
cout << "栈为空" << endl;
return;
}
else
{
while(pt != NULL)
{
cout << "第" << i << "个栈数据为:" ;
cout << pt->data << endl;
pt = pt->link;
i++;
}
}
}
void setEmpty(pnode top)//把栈置空
{
cout << "****************置空操作**************" << endl;
if(!isEmpty(top))
{
cout << "栈已经是空" << endl;
return;
}
else
{
top->link = NULL;
cout << "置空成功" << endl;
}
}
void destoryStack(pnode top)//清空销毁栈
{
cout << "****************销毁操作**************" << endl;
if(!isEmpty(top))
{
cout << "栈已经为空" << endl;
return;
}
else
{
pnode temp;
while(top->link != NULL)
{
temp = top->link;
top->link = temp->link;
free(temp);
}
cout << "销毁成功" << endl;
}
}
如果发现这段代码有任何疑义,或者有问题的地方请指出来,共同进步,谢谢!
c++实现链式栈的基本操作
最新推荐文章于 2025-07-09 18:28:25 发布