[DS][3-21]Implement two stacking using only one array

Source: 

Data Structures and Algorithm Analysis in C

The second edition (English version)

P87  3.21


Requirement:

write a routines to implement two stacks using only one array. Your stack routines should not declare an overflow unless every slot in the array is used.


Analysis:

(Will be updated later


Answer:

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

#define MAX_SIZE 100

void initialize(void);
int push(int *tail,int info);
int pop(int *tail);
int find_free(void);


struct{
	int info;
	int pre;
	int avaliable;
} stack[MAX_SIZE];

int storage = MAX_SIZE;
int head_1,head_2;
int tail_1,tail_2;


int main(void){
	int temp;
	initialize();
	temp = find_free();
	printf("%d \n",temp);
	return 0;
}

void initialize(void){
	for(int i = 0;i < MAX_SIZE;i++)
		stack[i].avaliable = 1;//marked as avaliable
}

int find_free(void){
	for(int i = 0;i < MAX_SIZE;i++)
		if(stack[i].avaliable) return i;
}

int push(int *tail,int info){
	int temp;
	temp = find_free();
	stack[temp].pre = *tail;
	stact[temp].info = info;
	stack[temp].avaliable = 0;
	*tail = temp;
	storage--;
}

int pop(int *tail){
	int info;
	info = stack[*tail].info;
	stack[*tail].avaliable = 0;
	*tail = stack[*tail].pre;
	storage++;
	return info;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值