栈的顺序存储实现 特点LIFO
顺序栈数据类型
typedef int DataType;
typedef struct
{
//数组存储数据
DataType buf[MAX];
//记录当前栈顶位置
int top;
}SeqStack;
常用操作
1.创建空的顺序栈,top == -1
SeqStack *create_empty_seqstack()
{
在堆区为顺序栈分配空间,用指针s
s->top = -1;
返回s
}
2.判空
int is_empty_seqstack(SeqStack *s)
{}
3.判满 top == MAX - 1
int is_full_seqstack(SeqStack *s)
{}
4.入栈,先移动top,再插入数据
int push_seqstack(SeqStack *s,DataType data)
{
}
5.出栈,先取出数据,再移动top
DataType pop_seqstack(SeqStack *s)
{
}
6.获得栈顶元素
DataType get_top_data(SeqStack *s)
{}
#ifndef __HEAD__H
#define __HEAD__H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10
typedef int DataType;
typedef struct
{
//数组存储数据
DataType buf[MAX];
//记录当前栈顶位置
int top;
}Seqstack;
extern Seqstack *create_empty_stack();
extern int is_empty_stack(Seqstack *s);
extern int is_full_stack(Seqstack *s);
extern int push(Seqstack *s,DataType data);
extern DataType pop(Seqstack *s);
extern DataType GetTop(Seqstack *s);
#endif
#include "head.h"
//创建新的数据栈,栈顶top = -1
Seqstack *create_empty_stack()
{
Seqstack *s = NULL;
s = (Seqstack *)malloc(sizeof(Seqstack));
s->top = -1;
return s;//修改前为返回0.这里应该返回栈头s
}
//栈判空
int is_empty_stack(Seqstack *s)
{
return s->top == -1;
//return (s->top == -1 ? 1 : 0)
}
//栈判满
int is_full_stack(Seqstack *s)
{
return s->top == MAX - 1;
}
//数据入栈
int push(Seqstack *s,DataType data)
{
//s->top++;
s->buf[++s->top] = data;//前置++优先级低于->
return 0;
}
//数据出栈
DataType pop(Seqstack *s)
{
//s->top--;
return s->buf[s->top--];
}
//取出栈顶元素
DataType GetTop(Seqstack *s)
{
return s->buf[s->top];
}
#include "head.h"
int main()
{
int i = 0;
Seqstack *s = NULL;
s = create_empty_stack();
while(!is_full_stack(s))
{
push(s,i++);
}
//获取栈顶值
printf("Top:%d\n",GetTop(s));
//栈顶出栈
printf("pop : %d\n",pop(s));
while(!is_empty_stack(s))
{
printf("%-3d",pop(s));
}
putchar('\n');
return 0;
}
//makefile
OBJS = main.o stackfun.o
CC = gcc
CFLAGS = -Wall -g
app:$(OBJS)
$(CC) $(CFLAGS) $^ -o $@
clean:
$(RM) *.o app