2.2栈的顺序结构->共享空间

来源:互联网 发布:mac键盘失灵只有开机键 编辑:程序博客网 时间:2024/06/06 11:43

参考《大话数据结构》:

环境:ubuntu16.04 vim

文件名称:sqdoublestack.h sqdoublestack.c main.c Makefile(放到同一个目录下)

实现功能:共享空间栈的初始化,入栈,出栈

1.sqdoublestack.h头文件

#ifndef __SQDOUBLESTACK_HEAD__#define __SQDOUBLESTACK_HEAD__#include <stdio.h>#include <stdlib.h>#define MAXSIZE 20#define OK 0#define ERROR -1#define TRUE 1#define FALSE 0typedef int ElemType;typedef int Status;typedef struct{ElemType data[MAXSIZE];int top1;//栈1栈顶指针int top2;//栈2栈顶指针}SqDoubleStack;/*extern 是变量或函数的申明,告诉编译器在其它文件中找这个变量或函数的定义*//**初始化一个栈,让top1栈顶元素下标为-1,让top2栈顶元素下标为MAXSIZE*s[IN, OUT]执行操作的共享栈*/extern void StackInit(SqDoubleStack *s);/**插入新的栈顶元素*s[IN, OUT]执行操作的共享栈*e[IN]要插入栈顶的元素*stackNumber  [IN]要进行操作的栈编号,1为栈1,2为栈2*/extern Status Push(SqDoubleStack *s, ElemType e, int stackNumber);/**若栈不空,则删除s的栈顶元素,用e返回其值,并返回OK,否则返回ERROR*s[IN, OUT]执行操作的共享栈*e[IN, OUT]要删除的栈顶元素*stackNumber  [IN]要进行操作的栈编号,1为栈1,2为栈2*/extern Status Pop(SqDoubleStack *s, ElemType *e, int stackNumber);#endif
2.sqdoublestack.c文件

#include "sqdoublestack.h"/*初始化栈*/void StackInit(SqDoubleStack *s){s->top1 = -1;//栈1的顶端指向-1s->top2 = MAXSIZE;//栈2的顶端指向数组的最大值处}/*插入元素e为新的栈顶元素*/Status Push(SqDoubleStack *s, ElemType e, int stackNumber){if (s->top1 + 1 == s->top2)//栈满{printf("栈已满,无法插入新的元素.\n");return ERROR;}if (stackNumber == 1)//表示是栈1中要插入元素{s->data[++s->top1] = e;//栈顶元素下标加1赋值}if (stackNumber == 2){s->data[--s->top2] = e;//栈顶元素下标减1赋值}return OK;}/*若栈不空,则删除s的栈顶元素,用e返回其值,并返回OK;否则返回ERROR*/Status Pop(SqDoubleStack *s, ElemType *e, int stackNumber){if (stackNumber == 1){if (s->top1 == -1){printf("栈1是空栈!\n");return ERROR;}*e = s->data[s->top1--];//栈顶元素出栈,栈顶下标减1}if (stackNumber == 2){if (s->top2 == MAXSIZE){printf("栈2是空栈!\n");return ERROR;}*e = s->data[s->top2++];//栈顶元素出栈,栈顶下标加1}return OK;}

3.main.c文件

#include "sqdoublestack.h"int main(){SqDoubleStack s;//初始化栈StackInit(&s);//栈1入栈if (Push(&s, 3, 1)){printf("push failed!\n");return ERROR;}printf("s.data[s.top1]:%d\n", s.data[s.top1]);//栈1出栈ElemType e = 0;if (Pop(&s, &e, 1)){printf("pop failed!\n");return ERROR;}printf("e:%d\n", e);//栈2入栈if (Push(&s, 4, 2)){printf("push failed!\n");return ERROR;}printf("s.data[s.top2]:%d\n", s.data[s.top2]);//栈2出栈if (Pop(&s, &e, 2)){printf("pop failed!\n");return ERROR;}printf("e:%d\n", e);return OK;}

4.Makefile文件

#Makefile for building programmingsOBJS=sqdoublestack.o main.oCC=gccCFLAGS=-Wall -gTARGET=sqdoublestackTARGET:$(OBJS)$(CC) $(OBJS) -o $(TARGET)sqdoublestack.o:sqdoublestack.c sqdoublestack.h$(CC) $(CFLAGS) -c $< -o $@main.o:main.c sqdoublestack.h$(CC) $(CFLAGS) -c $< -o $@.PHONY:cleanclean:rm *.o sqdoublestack

5.运行结果


0 0
原创粉丝点击