链栈基本操作
LStack *CreateStack(LStack *s,int n);
void Display(LStack *s);
LStack *Push(LStack *s,int n);
LStack *Pop(LStack *s);
void Top(LStack *s);
结构体定义
typedef struct LinkStack
{
int data;
struct LinkStack *next;
}LStack;
运行代码
#include"stdafx.h"
#include<iostream>
using namespace std;
typedef struct LinkStack
{
int data;
struct LinkStack *next;
}LStack;
LStack *CreateStack(LStack *s,int n);
void Display(LStack *s);
LStack *Push(LStack *s,int n);
LStack *Pop(LStack *s);
void Top(LStack *s);
int main()
{
LStack *s=NULL;
s=CreateStack(s,10);
s=Push(s,11);
s=Pop(s);
s=Pop(s);
s=Pop(s);
s=Push(s,100);
system("pause");
return 0;
}
LStack *CreateStack(LStack *s,int n)
{
LStack *p;
for(int i=0;i<n;i++)
{
p=new LStack;
p->data=i+1;
p->next=s;
s=p;
}
Display(s);
return s;
}
LStack *Push(LStack *s,int n)
{
cout<<n<<"压栈,";
LStack *p=new LStack;
p->data = n;
p->next=s;
s=p;
Display(s);
return s;
}
LStack *Pop(LStack *s)
{
if(s)
{
cout<<s->data<<"出栈,";
LStack *p=s;
s=s->next;
free(p);
if(s)
Display(s);
else
{
s=NULL;
cout<<"全部出栈";
return s;
}
}
else
{
cout<<"栈内无元素";
}
return s;
}
void Top(LStack *s)
{
if(s)
cout<<";栈顶元素:"<<s->data<<endl;
else
cout<<"栈空"<<endl;
}
void Display(LStack *s)
{
LStack *p=s;
cout<<"栈内元素:";
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
Top(s);
cout<<endl<<endl;
}
运行结果