用一个数组表示两个栈,只要数组有空间,往栈中添加元素就能成功
2016-02-24 19:09
330 查看
#include <stdio.h> #include <stdlib.h> #define MAXSIZE 6 /* 用一个数组表示两个栈,只要数组有空间,往栈中添加元素就能成功。 */ typedef int ElementType; typedef struct{ ElementType Data[MAXSIZE]; int top1; int top2; }Stack; // 创建一个空的栈 Stack* CreateStack( ); //压入栈 void Push(Stack* sp,ElementType item,int tag); //取出最上端的元素 ElementType Pop(Stack* sp,int tag); int main(){ Stack* sp=CreateStack(10); ElementType item; Push(sp,1,1); Push(sp,2,1); Push(sp,1,2); Push(sp,2,2); item=Pop(sp,1); printf("1pop:%d\n",item); item=Pop(sp,1); printf("1pop:%d\n",item); item=Pop(sp,2); printf("2pop:%d\n",item); item=Pop(sp,2); printf("2pop:%d\n",item); return 0; } Stack* CreateStack() { Stack* s=(Stack*)malloc(sizeof(Stack)); s->top1=-1; s->top2=MAXSIZE; return s; } void Push(Stack* sp,ElementType item,int tag) { //判断是否已满 if(sp->top2-sp->top1==1){ printf("栈已满\n"); return; } else{ if(tag==1) { sp->Data[++(sp->top1)]=item; }else { sp->Data[--(sp->top2)]=item; } } } ElementType Pop(Stack* sp,int tag) { ElementType data; if(tag==1) { if(sp->top1==-1) { printf("栈1已空\n"); return NULL; }else { data=sp->Data[(sp->top1)--]; } }else { if(sp->top2==(MAXSIZE+1)) { printf("栈2已空\n"); return NULL; }else { data=sp->Data[(sp->top2)++]; } } }
相关文章推荐
- shell关闭___启动tomcat
- 传输层
- .gitignore更改后无效
- linux图形界面基本知识(X、X11、Xfree86、Xorg、GNOME、KDE之间的关系)
- Sql Server 强制断开数据库已有连接的方法
- Linux内核分析:实验一
- struts2项目配置文件及处理流程
- java.lang.NoClassDefFoundError: org/apache/ibatis/mapping/DatabaseIdProvider
- CentOS 6.5 英文提示修改为中文提示的方法
- POJ - 1442 Black Box
- Spring AOP实现日志服务
- 网络的理解
- 【BZOJ2049】[Sdoi2008]Cave 洞穴勘测【Link-Cut Tree】
- GridView中第一个item不显示,以及显示方式不正确的调整方式。
- OC基础-03Foundation中的简单类和数据类型
- IOS Apps 开发(Swift)(2)——Learn the Essentials of Swift(2)
- Spring AOP与IOC以及自定义注解
- 《数据结构与算法分析(c描述)》—— 插入排序&希尔排序
- java swing的默人LookAndFeel
- LeetCode Algorithms #232 <Implement Queue using Stacks>