C++实现链栈的各项操作
代码如下
#include <iostream>
using namespace std;
typedef struct Lnode//结点构建
{
int data;
struct Lnode *next;
}Lnode;
void initstack(Lnode *&C)//初始化链栈
{
cout<<" 初始化栈 "<<endl;
C=(Lnode*)malloc(sizeof(Lnode));
C->next=NULL;
}
int isempty(Lnode *C)//判空
{
if(C->next==NULL)
{
cout<<" 栈为空 "<<endl;
return 1;//空则返回1
}
else
{
cout<<" 栈不为空 "<<endl;
return 0;//不空返回0
}
}
void push(Lnode *&C,int x)//进栈
{
struct Lnode *S;//为新进元素创建结点让S指针指向它
S=(Lnode*)malloc(sizeof(Lnode));//为新进元素开辟空间
S->next=NULL;
S->data=x;//将输入元素赋给新创建结点的值域
S->next=C->next;//方法和头插法建立单链表类似
C->next=S;
}
int pop(Lnode *&C,int &m)//出栈
{
struct Lnode *S;//为出栈元素建立结点指针S
cout<<" 删除并得到栈顶元素: ";
if(C->next==NULL)//判空
{
return 0;//空返回0
}
S=C->next;//找到出栈的元素结点,用S指针指向它
m=S->data;//赋值
C->next=S->next;//单链表删除
free(S);//释放空间
cout<<m<<endl;
return 1;
}
int gettop(Lnode *C,int &e)//用e返回栈顶元素的值
{
cout<<" 栈顶元素为: ";
if(C->next==NULL)//判空
{
cout<<"NULL"<<endl;
return 0;
}
else
{
e=C->next->data;//取出栈顶元素的值赋给e
cout<<e<<endl;
return 1;
}
return 2;
}
int main()
{
struct Lnode Lnode;//建立结构体实例
struct Lnode *C;//建立结构体指针
C=&Lnode;//让结构体指针C指向实例Lnode
int x;int m;int e;int i=0;
initstack(C);
isempty(C);
gettop(C,e);
cout<<" 请输入插入的元素:";
cin>>x;
push(C,x);
isempty(C);
gettop(C,e);
pop(C,m);
isempty(C);
gettop(C,e);
return 0;
}
运行结果如下
本文详细介绍使用C++实现链式栈的各种基本操作,包括初始化、判断是否为空、入栈、出栈及获取栈顶元素等。通过具体代码示例,帮助读者深入理解链栈的运作原理。

被折叠的 条评论
为什么被折叠?



