您的位置:首页 > 编程语言 > C语言/C++

链式栈的基本操作实现c++

2016-08-06 20:50 477 查看
注:若有错误或需要补充的内容请告知,新手上路,谢谢。

#include<stdlib.h>
#include<stdio.h>
#include<cstring>
#include<string>
#include<algorithm>
#include<math.h>
#include<ctype.h>
using namespace std;

/*结点结构体*/
typedef struct node
{
int data;
struct node *next;
}stacknode;
/*链式栈结构体*/
typedef struct linkstack
{
stacknode *base;
stacknode *top;
}linkstack;
/*链式栈初始化*/
linkstack *init_stack()
{
linkstack *s;
s=(linkstack*)malloc(sizeof(linkstack));
s->base=(stacknode*)malloc(sizeof(stacknode));
s->top=s->base;
s->base->next=NULL;
return s;
}
/*判断链式栈空*/
bool is_empty_linkstack(linkstack s)
{
if(s.base==s.top)
{
return true;
}
else
{
return false;
}
}
/*链式栈入栈*/
void push(linkstack *s,int e)
{
stacknode *p;
p=(stacknode*)malloc(sizeof(stacknode));
p->data=e;
p->next=s->top;
s->top=p;
}
/*链式栈出栈*/
void pop(linkstack *s,int &e)
{
if(is_empty_linkstack(*s))
{
printf("栈空");
}
else
{
stacknode *p=s->top;
e=p->data;
s->top=p->next;
free(p);
}
}
/*销毁栈*/
void delete_stack(linkstack *s)
{
stacknode *p;
while(!is_empty_linkstack(*s))
{
p=s->top;
s->top=p->next;
free(p);
}
printf("栈销毁成功\n");
}
/*链式栈的长度*/
int length(linkstack s)
{
stacknode *p=s.top;
int i=0;
while(p!=s.base)
{
i++;
p=p->next;
}
return i;
}
/*返回栈顶元素*/
void get_top(linkstack s,int &e)
{
if(is_empty_linkstack(s))
{
printf("栈空");
}
else
{
e=s.top->data;
}
}
int main()
{
linkstack *s;
int l,e;
s=init_stack();
printf("请输入入栈的元素个数:");
scanf("%d",&l);
printf("请依次输入要入栈的元素:");
for(;l>0;l--)
{
scanf("%d",&e);
push(s,e);
}
printf("依次出栈的元素为:");
while(!is_empty_linkstack(*s))
{
pop(s,e);
printf("%d",e);
}
printf("\n");
delete_stack(s);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 链式栈