双栈

双栈意思就是双向栈,基本思想就是在一段内存里面,栈从两边分别向中间生长,这样可以提高内存的利用率。下面是C的实现代码,仅仅是基本的功能,重在于思想。

#include <stdio.h>
#include <stdlib.h>

#define INIT_STACK_SIZE 100

typedef int ElemType;
typedef struct DoubleStack{
	ElemType *array;
	int top1;	//SP for stack1
	int top2;	//SP for stack2
}DouStack,*pDouStack;

void InitialDouStack(pDouStack S);
void Push(pDouStack S,ElemType add_data,int flags);//flags==1,for stack1;flags==2,for stack2
void Pop(pDouStack S,ElemType *del_data,int flags);//flags==1,for stack1;flags==2,for stack2
void PrintDoubleStack(pDouStack S);

int main()
{
	DouStack S;
	InitialDouStack(&S);	
	for(int i = 1; i <= 20; ++i)
	{
		Push(&S,i,i%2 + 1);//for debug,flag2 is 1 or 2
	}
	PrintDoubleStack(&S);	//print stack1 and stack2
	ElemType temp = 0;	//accept data pop from stack;
	for(int i = 1; i <= 25; ++i)
	{
		Pop(&S,&temp,i%2 + 1);
	}
	PrintDoubleStack(&S);	

	return 0;
}

void InitialDouStack(pDouStack S)
{
	S->array = (ElemType *)calloc(INIT_STACK_SIZE,sizeof(DouStack));
	if(!S->array)
	{
		printf("allocate memory error \n");
		return ;
	}
	S->top1 = 0;
	S->top2 = INIT_STACK_SIZE;
}

void Push(pDouStack S,ElemType add_data,int flags)
{
	if(S->top2 == S->top1)
	{
		printf("Full double stack\n");
		return ;
	}	
	switch(flags)
	{
		case 1:	//push into stack1
			S->array[S->top1++] = add_data;			
			break;
		case 2: //push into stack2
			S->array[--S->top2] = add_data;			
			break;
		default :
			return;
	}
	return;
}

void PrintDoubleStack(pDouStack S)
{
	int top1 = S->top1;
	int top2 = S->top2;
	
	printf("Stack 1 : \n");
	while(top1)
	{
		printf("Stack 1 %d : %d \n",top1,S->array[--top1]);
	}
	
	printf("Stack 2 : \n");
	while(top2 < INIT_STACK_SIZE)
	{
		printf("Stack 2 %d : %d \n",top2,S->array[top2++]);
	}
}

void Pop(pDouStack S,ElemType *del_data,int flags)
{
	switch(flags)
	{
		case 1:	//pop from stack1
			if(S->top1 == 0)
			{	
				printf("Stack1 is empty!\n");
				return;
			}
			*del_data = S->array[--S->top1];			
			break;
		case 2: //pop from stack2
			if(S->top2 == INIT_STACK_SIZE)
			{
				printf("Stack2 is empty!\n");
				return;
			}
		        *del_data = S->array[S->top2++];			
			break; 
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值