数据结构 共享栈(一个数组实现两个栈)

题目解析:

数据结构 共享栈(一个数组实现两个栈)_第1张图片

代码:

#include

#define Max_size 1000

typedef char DataType;
typedef struct shareStack
{
	DataType data[Max_size];
	int top1;
	int top2;
}shareStack;

//初始化
void shareStackInit(shareStack* stack)
{
	if(stack == NULL)
	{
		//非法输入
		return;
	}
	stack->top1 = 0;
	stack->top2 = Max_size;
	return;
}

//打印栈1
void shareStackPrint1(shareStack* stack,const char* msg)
{
	printf("[%s]\n",msg);
	if(stack == NULL)	
	{
		//非法输入
		return;
	}
	int i = 0;
	for(i = 0; i< stack->top1;i++)
	{
		printf("%c ",stack->data[i]);
	}
	printf("\n");
}

//打印栈2
void shareStackPrint2(shareStack* stack,const char* msg)
{
	printf("[%s]\n",msg);
	if(stack == NULL)	
	{
		//非法输入
		return;
	}
	int i = Max_size;
	for(;i > stack->top2;i--)	
	{
		printf("%c ",stack->data[i]);
	}
	printf("\n");
}

//栈1插入元素
void shareStackPush1(shareStack* stack,DataType value)
{
	if(stack == NULL)
	{
		//非法输入
		return;
	}
	if(stack->top1 == stack->top2)
	{
		//达到共享栈上限
		return;
	}
	stack->data[stack->top1++] = value;
	return;
}



//栈2插入元素
void shareStackPush2(shareStack* stack,DataType value)
{
	if(stack == NULL)
	{
		return;
	}
	if(stack->top1 == stack->top2)
	{
		//达到共享栈上限
		return;
	}
	stack->data[stack->top2--] = value;
	return;
}

//栈1出栈
void shareStackPop1(shareStack* stack)
{
	if(stack == NULL)
	{
		//非法输入
		return;
	}
	stack->top1--;
	return;
}

//栈2出栈
void shareStackPop2(shareStack* stack)
{
	if(stack == NULL)
	{
		//非法输入
		return;
	}
	stack->top2++;
	return;
}

//栈1取栈顶元素
int shareStackGet1(shareStack* stack,char* value)
{
	if(stack == NULL)
	{
		return 0;
	}
	*value = stack->data[stack->top1-1];
	return 1;
}


//栈2取栈顶元素
int shareStackGet2(shareStack* stack,char* value)
{
	if(stack == NULL)
	{
		return 0;
	}
	*value = stack->data[stack->top2+1];
	return 1;
}

//测试函数
void TestshareStack()
{
	char value;
	shareStack stack;
	shareStackInit(&stack);
	printf("\n=================栈1测试================\n");
	shareStackPush1(&stack,'a');
	shareStackPush1(&stack,'b');
	shareStackPush1(&stack,'c');
	shareStackPrint1(&stack,"共享栈1插入3个元素");
	shareStackPop1(&stack);
	shareStackPrint1(&stack,"共享栈1出栈1个元素");
	int ret = shareStackGet1(&stack,&value);
	printf("expect is [1|b],acutl is [%d|%c].\n",ret,value);

	printf("\n=================栈2测试================\n");
	shareStackPush2(&stack,'d');
	shareStackPush2(&stack,'e');
	shareStackPush2(&stack,'f');
	shareStackPrint2(&stack,"共享栈2插入3个元素");
	shareStackPop2(&stack);
	shareStackPrint2(&stack,"共享栈2出栈1个元素");
	ret = shareStackGet2(&stack,&value);
	printf("expect is [1|e],acutl is [%d|%c].\n",ret,value);

}


int main()
{
	TestshareStack();
	return 0;
}

运行结果:

数据结构 共享栈(一个数组实现两个栈)_第2张图片

你可能感兴趣的:(数据结构)