栈(顺序栈和链栈)
目录
一.顺序栈
#include<iostream>
using namespace std;
#define maxn 50
#define OK 1
#define ERROR 0
typedef struct
{
int date[maxn];
int top;
}Stack;
int init(Stack *s) //初始化
{
s->top = -1;
return OK;
}
int empty(Stack *s) //判断栈空
{
if(s->top == -1)
return OK;
else
return ERROR;
}
int length(Stack *s)
{
return s->top + 1;
}
int push(Stack *s,int e)
{
if(s->top == maxn-1) //栈满
return ERROR;
s->top++;
s->date[s->top] = e;
return OK;
}
int pop(Stack *s)
{
if(empty(s))
return ERROR;
s->top--;
return OK;
}
int top(Stack *s,int *e)
{
if(empty(s))
return ERROR;
*e = s->date[s->top];
return OK;
}
int main()
{
Stack s;
int e,i;
init(&s);
for(i=1;i<10;i++)
{
push(&s,i);
}
cout << "len:" << length(&s) << endl;
while(!empty(&s))
{
top(&s,&e);
cout << "top:" << e << endl;
pop(&s);
}
if(empty(&s))
cout << "empty!" << endl;
return 0;
}
二.链栈
#include<iostream>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define maxn 50
#define len sizeof(StackNode)
using namespace std;
typedef struct StackNode
{
int date;
struct StackNode *next;
}StackNode,*LinkStack;
int init(LinkStack &s)
{
s = NULL;
return OK;
}
int push(LinkStack &s,int e)
{
LinkStack p;
p = (LinkStack )malloc(sizeof(len));
p->date = e;
p->next = s;
s = p;
return OK;
}
int pop(LinkStack &s)
{
LinkStack p;
if(s == NULL)
return ERROR;
p = s;
s = s->next;
free(p);
return OK;
}
int top(LinkStack &s)
{
if(s == NULL)
return ERROR;
return s->date;
}
int main()
{
LinkStack s;
init(s);
for(int i=1;i<10;i++)
push(s,i);
while(s != NULL)
{
cout << "top:" << top(s) << endl;
pop(s);
}
return 0;
}