数据结构之链栈的基本操作(出栈,入栈,显示,求栈的长度)

//将12345依次入栈,取栈顶元素,将6,7入栈,求栈中元素个数,将7出栈,将6出栈,将5出栈,最后全部出栈依次输出
#include<iostream>
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define maxsize 100
using namespace std;
typedef struct node
{
int data;
struct node *next;
}lnode ,*linkstack;

void init(linkstack *top)
{
if( ( (*top)=(linkstack)malloc(sizeof(lnode)) )==NULL )//(给*top分配一个存储空间让top指向这个空间)
exit(-1);
(*top)->next=NULL;

}
int empty(linkstack top)
{
if(top->next==NULL)
return 1;
else
return 0;
}
int get(linkstack top,int *e)
{
lnode *p;
p=top->next;
if(!p)
{
cout<<"栈已空!";
return 0;
}
else
{
*e=p->data;
return 1;
}
}


int push(linkstack top,int e)
{
lnode *p;
if( (p=(linkstack)malloc(sizeof(lnode)))==NULL )//(给*top分配一个存储空间让top指向这个空间)
{
printf("分配内存失败");
exit(-1);
return 0;
}

p->data=e;
p->next=top->next;
top->next=p;
return 1;

}
int pop(linkstack top,int *e)
{
linkstack p=top->next;
if(p==NULL)
{
cout<<"栈已空!";
return 0;
}

top->next=p->next;
*e=p->data;
free(p);
return 1;
}


int length(linkstack top)
{
int i=0;
lnode *p=top;
while(p->next!=NULL)
{
p=p->next;
i++;
}
return i;
}

void clear(linkstack top)
{
lnode *p,*q;
p=top;
while(!p)
{
q=p;
p=p->next;
free(q);
}
}

int main()
{
linkstack s;
lnode *p;
int i;
int a[]={1,2,3,4,5};
int e;
init(&s);
cout<<"将12345依次入栈!"<<endl;
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
push(s,a[i]);
}

cout<<"栈顶元素为:";
if(get(s,&e)==0)
{
cout<<"栈为空";
return 0;
}
else
{
cout<<e;
cout<<endl;
}
cout<<"将6入栈"<<endl;
push(s,6);
cout<<"将7入栈"<<endl;
push(s,7);
cout<<"栈中元素个数为:"<<length(s);
cout<<endl;

cout<<"将7出栈"<<" ";
pop(s,&e);
cout<<"将6出栈"<<" ";
pop(s,&e);
cout<<"将5出栈"<<endl;
pop(s,&e);

cout<<"栈中元素个数为:"<<length(s);
cout<<endl;

cout<<"出栈元素的序列:";
while(!empty(s))
{
pop(s,&e);
cout<<e;
}
cout<<endl;

}

原文地址:https://www.cnblogs.com/mykonons/p/6600211.html