#include<stdio.h>
#include<stdlib.h>
#define maxsize 100
顺序栈结构体定义
typedef struct SqStack
{
int data[maxsize];
int top;
}SqStack;
链栈结构体定义
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
顺序栈初始化
void InitSqStack(SqStack &St)
{
St.top=-1;
}SqStack;
链栈初始化
void initStack(LNode *&st)
{
st=(LNode*)malloc(sizeof(LNode));
st->next=NULL;//制造一个头结点
}
顺序栈入栈
int push(SqStack &St,int e)
{
if(St.top==maxsize-1)
return 0;
++(St.top);
St.data[St.top]=e;
return 1;
}
链栈元素入栈(即元素头插法入链表)
void pushl(LNode *&st)
{
LNode *p;
p=(LNode*)malloc(sizeof(LNode));
scanf("%d",&p->data);
p->next=st->next;
st->next=p;
}
顺序栈元素出栈
int pop(SqStack &St)
{
int x;
if(St.top==-1)
return 0;
x=St.data[St.top];
--(St.top);
return 1;
}
链栈出栈
void popl(LNode *&st)
{
LNode *p;
p=(LNode*)malloc(sizeof(LNode));
if(st->next!=NULL)
{
p=st->next;
st->next=p->next;
free(p);
}
}
建顺序栈
int createStack(SqStack &S)
{
int n,e,count;
printf("请输入栈元素个数:");
scanf("%d",&n);
if(n>maxsize)
return 0;
InitSqStack(S);
count=0;
while(count<n)
{
scanf("%d",&e);
push(S,e);
count++;
}
return 1;
}
建链栈
void createStackl(LNode *&st)
{
int x;
int count=0;
printf("请输入栈长度");
scanf("%d",&x);
while(count<x)
{
pushl(st);
++count;
}
}
输出顺序栈
void show(SqStack St)
{
while(St.top!=-1)
{
printf("%d\t",St.data[St.top]);
pop(St);
}
}
输出链栈
void showl(LNode *st)
{
LNode *p;
p=st->next;
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
}
应用
int main()
{
SqStack S;
createStack(S);
show(S);
LNode *s;
initStack(s);
createStackl(s);
showl(s);
return 1;
}