码迷,mamicode.com
首页 > 编程语言 > 详细

用一个数组实现两个堆栈

时间:2016-12-08 03:35:48      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:技术分享   ast   void   struct   lib   tty   else   http   --   

技术分享

 

 

#include <stdio.h>
#include <stdlib.h>
#define ElementType int
const int MAXSIZE = 10;
typedef struct Node *DStack;
typedef struct Node{
	ElementType Data[MAXSIZE];
	int last0;
	int last1;
};

bool Push(int flag,DStack &S, ElementType X){//0代表插入栈0,1代表插入栈1 
	//printf("------------------------------------\n");
	if(S->last0==S->last1-1){
		printf("栈满\n");
		return 0;
	}
	//printf("------------------------------------\n");
	if(flag==0){
		S->Data[++S->last0] = X;
		return true;
	}else if(flag == 1){
		S->Data[--S->last1]=X;
		return true;
	}else{
		printf("插入序号有误\n");
		return false;
	}
}
ElementType Pop(int flag,&DStack S){
	if((flag==0 && S->last0==-1)||(flag==1 && S->last1 == MAXSIZE)){
		printf("栈空");
		return 0;
	}
	if(flag ==0)
		return S->Data[S->last0--];
	else if(flag ==1)
		return S->Data[S->last1++];
	else{
		printf("插入序号有误\n");
		return 0;
	}
}
void InintDStack(DStack &S){
	S = (DStack)malloc(sizeof(struct Node));
	S->last0 = -1;
	S->last1= MAXSIZE;
}
int main(){
	DStack S;
	InintDStack(S);
	
	for(int i = 0;i<12;i++){
		Push(i%2,S,i);
	}
	for(int i=0;i<12;i++){
		printf("%d\n",Pop(i%2,S));
	}
	return 0;
}

  

用一个数组实现两个堆栈

标签:技术分享   ast   void   struct   lib   tty   else   http   --   

原文地址:http://www.cnblogs.com/zangkuo/p/6143462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!