两栈共享空间

 两个相同类型的栈,可能第一个栈已经满了,但是第二个栈还是空的,将两个相同类型的栈合并在一起,可以节省一部分空间。

数组有两个端点,分别为两个栈的栈底,一个栈的栈底的位置为数组为0的地方,另一个栈的栈底为数组下标为SIZE-1的位置,SIZE为数组的长度。两个栈如果增加元素,就是两端点向中间延伸。

只要两个栈顶指针不碰面,元素就可以一直进栈。

 

 


头文件

#pragma once
//顺序栈
#define MAXSIZE 10
typedef struct DoubleStack
{
	int *elem;//数据
	int top1;//左边栈的栈顶指针
	int top2;//右边栈的栈顶指针
}DoubleStack,* PDoubleStack;
//初始化
void InitDoubleStack(PDoubleStack ps);
//入栈
bool Push(PDoubleStack ps,int val,int num);
//出栈
bool Pop(PDoubleStack ps,int  *rtval,int  num);
//清空
bool Clear(PDoubleStack ps);
//销毁
void Destroy(PDoubleStack ps);

cpp文件

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include"DoubleStack.h"

void InitDoubleStack(PDoubleStack ps)
{
	ps->elem = (int *) malloc (MAXSIZE *sizeof(int));
	ps->top1= 0;
	ps->top2 =MAXSIZE-1;
}

static bool IsFull(PDoubleStack ps)
{
	return ps->top1+1 == ps->top2;
}

bool IsEmpty(PDoubleStack ps)
{
	if(!(ps->top1 == 0 && ps->top2 == 0 ))
	{
		return false;
	}
	return true;
}


bool Push(PDoubleStack ps,int val,int num)
{
	assert(ps != NULL);
	if(ps == NULL)
	{
		return NULL;
	}
	if(IsFull(ps))
	{
	    return false;
	}
	if(num == 1)
	{
		ps->elem[ps->top1] = val;
		ps->top1++;
	}
	else if(num == 2)
	{
		ps->elem[ps->top2] = val;
		ps->top2--;
	}
	return true;
}
//num表示的是要进哪个栈
bool Pop(PDoubleStack ps,int  *rtval,int num)
{
	assert(ps != NULL && rtval != NULL);
	if(ps == NULL)
	{
		return NULL;
	}

	if(!(IsEmpty(ps)))
	{
		if(num  == 1)
		{
			*rtval = ps->elem[--ps->top1];
		}
		else if(num  == 2)
		{
			*rtval = ps->elem[++ps->top2];
		}
		return true;
	}

	return false;
}

bool Clear(PDoubleStack ps)
{
	ps->top1 = 0;
	ps->top2 = MAXSIZE -1;
	return true;
}

void Destroy(PDoubleStack ps)
{
	free(ps->elem);
	ps -> top1 = 0;
	ps -> top2 = 0;
}

主函数

#include<stdlib.h>
#include"DoubleStack.h"

int main()
{
	DoubleStack sta;
	InitDoubleStack(&sta);
	for(int i = 0;i<7;i++)
	{
		 Push(&sta,i,1);
	}
	for(int i = 0;i<2;i++)
	{
		 Push(&sta,i+10,2);
	}
	int rtval = -1;
	Pop(&sta,&rtval,1);
	printf("%d\n",rtval);
	for(int i = 0;i<10;i++)
	{
		 printf("%d\n",sta.elem[i]);
	}

	Destroy(&sta);
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值