共享栈(Shared Stack)实现

本文介绍了如何实现一个共享栈(Shared Stack)。该栈通过一个数组同时存放两个栈的数据,其中:

代码

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

/*
 * 共享栈(Shared Stack)结构体定义
 * 用一个数组 elements 来同时存放两个栈的数据
 * 栈1 从左向右增长(top1 从 -1 开始)
 * 栈2 从右向左增长(top2 从 size 开始)
 * 当 top1 + 1 == top2 时,表示栈已满
 */
typedef struct {
	int *elements;
	int top1;
	int top2;
	int size;
}Sharedstack; 

/*
 * 初始化共享栈
 * 参数:
 *   obj  —— 指向共享栈结构的指针
 *   size —— 共享数组的大小
 * 返回值:
 *   true  初始化成功
 *   false 内存分配失败
 */
bool SharedstackInit(Sharedstack *obj,int size){
	obj->elements = (int*)malloc(size*sizeof(int));
	if(obj->elements == NULL)return false;
	obj->top1 = -1;
	obj->top2 = size;
	obj->size = size; 
	return true;
}
/*
 * 判断共享栈是否为空
 * 当两个栈都为空时返回 true
 */
bool SharedstackIsempty(Sharedstack obj){
	if(obj.top1 == -1 && obj.top2 == obj.size)
	    return true;
	return false;
}
/*
 * 入栈操作(针对栈1)
 * 从左向右增长
 */
bool Sharedstack1en(Sharedstack *obj,int value){
	if(obj->top1 + 1 == obj->top2)return false;
	obj->top1 ++;
	obj->elements[obj->top1] = value;
	return true;
}
/*
 * 入栈操作(针对栈2)
 * 从右向左增长
 */
bool Sharedstack2en(Sharedstack *obj,int value){
	if(obj->top1 + 1 == obj->top2)return false;
	obj->top2 --;
	obj->elements[obj->top2] = value;
	return true;
}
/*
 * 出栈操作(针对栈1)
 * 仅修改 top1 指针即可
 */
bool Sharedstack1de(Sharedstack *obj){
	if(obj->top1 == -1)return false;
	obj->top1 --;
	return true;
}
/*
 * 出栈操作(针对栈2)
 * 仅修改 top2 指针即可
 */
bool Sharedstack2de(Sharedstack *obj){
	if(obj->top2 == obj->size)return false;
	obj->top2 ++;
	return true;
}
/*
 * 取栈顶元素(栈1)
 * 若栈为空返回 -1
 */
int Sharedstack1top(Sharedstack *obj){
	if(obj->top1 == -1)return -1;
	return obj->elements[obj->top1];
}
/*
 * 取栈顶元素(栈2)
 * 若栈为空返回 -1
 */
int Sharedstack2top(Sharedstack *obj){
	if(obj->top2 == obj->size)return -1;
	return obj->elements[obj->top2];
}
/*
 * 释放共享栈内存(只释放堆区数组)
 * 注意:不能对结构体本身调用 free()
 * 因为它是定义在栈区的局部变量
 */
void freeSharedstack(Sharedstack *obj){
	free(obj->elements);
}
/*
 * 主函数测试:
 * 1. 初始化共享栈
 * 2. 同时向两个栈中压入数据
 * 3. 分别输出两个栈的内容
 */
int main(){
	Sharedstack a;
	SharedstackInit(&a, 10);
	printf("%d\n", SharedstackIsempty(a));
	for(int i = 1; i <= 5; i++){
		Sharedstack1en(&a, i);
		Sharedstack2en(&a, i);
	}
	for(int i = 1; i <= 5; i++){
		printf("%d\n", Sharedstack1top(&a));
		Sharedstack1de(&a);
	}
	freeSharedstack(&a);
	return 0;
}