顺序栈
基本定义
- 栈是仅限定在表尾进行插入和删除的操作的线性表
- LIFO:last in first out–后进先出
- 一片连续的存储单元
SeqStack.h
#ifndef __SEQSTACK_H__
#define __SEQSTACK_H__
#define element x
typedef struct SeqStack
{
element *data;
element maxlen;
element top;
}SeqStack;
SeqStack *InitStack(int maxL);
void destroy(SeqStack *s);
void clear(SeqStack *s);
int StackisEmpty(SeqStack *s);
int StackLength(SeqStack *s);
int push(SeqStack *s,elelment x);
int pop(SeqStack *s,elelment *e);
int GetTop(SeqStack *s, Selement *e);
void print(SeqStack *s);
#endif
SeqStack.c
#include<stdio.h>
#include<stdlib.h>
#include "SeqStack.h"
SeqStack *InitStack(int maxL)
{
SeqStack *s = malloc(sizeof(*s));
s->data = maollc(sizeof(element) * maxL);
s->maxlen = maxL;
s->top = -1;
return s;
}
void destroy(SeqStack *s)
{
if(s == NULL)
{
return;
}
free(s->data);
free(s);
}
void clear(SeqStack *s)
{
if(s == NULL)
{
return;
}
s->top = -1;
}
int StackisEmpty(SeqStack *s)
{
if(s == NULL || s->top == -1)
{
return 1;
}
return 0;
}
int StackLength(SeqStack *s)
{
if(s == NULL)
{
return 0;
}
return s->top+1;
}
int push(SeqStack *s,elelment x)
{
if(s == NULL || s->top+1 == s->maxlen)
{
return 0;
}
s->data[++s->top] = x;
return 1;
}
int pop(SeqStack *s,elelment *e)
{
if(s == NULL || s->top = -1)
{
return 0;
}
*e = s->data[s->top--];
printf("出栈数为:%d\n",*e);
return 1;
}
int GetTop(SeqStack *s, Selement *e)
{
if(s == NULL || s->top == -1)
{
return 0;
}
*e = s->data[s->top];
return 1;
}
void print(SeqStack *s)
{
int i;
for(i = 0;i < s->maxlen;i++)
{
printf("第%d个元素值是%d\n",i+1,s->data[i]);
}
}
main.c
#include<stdio.h>
#include<stdlib.h>
#include "SeqStack.h"
int main()
{
int maxL,x,i;
printf("请输入栈最多元素的个数:\n");
scanf("%d",&maxL);
SeqStack *s = InitStack(maxL);
printf("请输入入栈元素:\n");
for(x = 0;x < maxL;x++)
{
scanf("%d",&i);
push(s,i);
}
print(s);
for(x = maxL-1;x > -1;x++)
{
pop(s,&i);
}
return 0;
}