三、堆栈的一般(数组)实现

#include <stdio.h>
#define max 20
/*通常用一维数组来实现堆栈*/
typedef struct SNode* stack;/*stack->stack*/
struct SNode {
	int data[max];
	int top;/*下标,就是最后一个数,不是指向它后面的空位置*/
};
/*建立空栈*/
stack make_empty_stack(void)
{
	stack ptrs = malloc(sizeof(struct SNode));
	ptrs->top = -1;
	return ptrs;
}
/*入栈*/
void push(stack ptrs, int item)
{
	if (ptrs->top == max - 1)
	{
		printf("满了\n");
		return;
	}
	else
	{
		ptrs->data[++ptrs->top] = item;
		return;
	}
}
/*出栈*/
int pop(stack ptrs)
{
	if (ptrs->top < 0)
	{
		printf("栈空\n");
		return;
	}
	else
	{
		int s = ptrs->data[ptrs->top--];
		return s;
	}
}
/*用一维数组实现2个堆栈,即从两头相向出发*/
struct Double_stack {
	int data[max];
	int top1;
	int top2;
};
typedef struct Double_stack* dstack;
/*建立空栈*/
dstack make_empty_double_stack(void)
{
	dstack ptrs = malloc(sizeof(struct Double_stack));
	ptrs->top1 = -1;
	ptrs->top2 = max;
}
/*入栈操作*/
void push_dstack(dstack ptrs, int item,int tag)
{
	if ((ptrs->top2 - ptrs->top1) == 1)//不是0,是1,要注意
	{
		printf("栈满\n");
		return;
	}
	else if (tag == 1)
	{
		ptrs->data[++ptrs->top1] = item; 
		return;
	}
	else if (tag == 2)
	{
		ptrs->data[--ptrs->top2] = item;
		return;
	}
}
/*出栈操作*/
int pop_dstack(dstack ptrs, int tag)
{
	if (tag == 1)
	{
		if (ptrs->top1 == -1)
		{
			printf("栈空\n");
			return NULL;
		}
		else
		{
			int p = ptrs->data[ptrs->top1--];
			return p;
		}
	}
	else
	{
		if (ptrs->top2 = 20)
		{
			printf("栈空\n");
			return NULL;
		}
		else
		{
			int p = ptrs->data[ptrs->top2++];
			return p;
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值