两个相同类型的栈,可能第一个栈已经满了,但是第二个栈还是空的,将两个相同类型的栈合并在一起,可以节省一部分空间。
数组有两个端点,分别为两个栈的栈底,一个栈的栈底的位置为数组为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;
}