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;
}