两栈共享空间

结构如下:

#include<iostream>
#include<stdlib.h>

#define MAXSIZE  10
typedef struct stack
{
	int data[MAXSIZE];
	int top1;
	int top2;
}seqdoublestack;

extern void initseqdoublestack(seqdoublestack* s);
extern int pushseqdoublestack(seqdoublestack* s, int value, int number);
extern int popseqdoublestack(seqdoublestack* s, int value, int number);
extern void printseqdoublestack(seqdoublestack* s);

#endif

//相关操作

#include"seqdoublestack.h"

void initseqdoublestack(seqdoublestack* s)
{

	s->top1 = -1;

	s->top2 = MAXSIZE;

}

int pushseqdoublestack(seqdoublestack* s, int value, int number)
{
	if (s->top1 + 1 == s->top2)
	{
		return 0;
	}

	if (number == 1)
	{
		s->data[++s->top1] = value;
	}
	else if (number == 2)
	{

		s->data[--s->top2] = value;
	}

	return 1;
}

int popseqdoublestack(seqdoublestack* s, int value, int number)
{
	if (number == 1)
	{
		if (s->top1 == -1)
		{
			return 0;
		}

		value = s->data[s->top1--];

	}
	else if (number == 2)
	{
		if (s->top2 == MAXSIZE)
		{
			return 0;
		}

		value = s->data[s->top2++];
	}

	return 1;

}

void printseqdoublestack(seqdoublestack* s)
{
	int i = 0;

	for (i = 0; i <= MAXSIZE - 1; i++)
	{
		printf("%d\t", s->data[i]);
	}

	return;
}

//测试

#include"seqdoublestack.h"
int main()
{

	int i = 0;

	seqdoublestack* s = NULL;

	s = (seqdoublestack*)malloc(sizeof(seqdoublestack));

	initseqdoublestack(s);

	for (i = 0; i <MAXSIZE; i++)
	{
		pushseqdoublestack(s, i + 1, 1);
	}

	printseqdoublestack(s);

	printf("\n");

	system("pause");

	return 0;
}

//在一个数组中设置两个栈,其中一个栈的栈底为数组的始端(下标0),另一个栈底为数组的末端(下标MAXSIZE-1)。如果增加元素,两个栈顶指针就向中间移动,若删除数据则向两端移动。

在这里插入图片描述

发布了150 篇原创文章 · 获赞 81 · 访问量 6471

猜你喜欢

转载自blog.csdn.net/qq_38158479/article/details/104051362