Question: A stack is a container that can be defined in terms of an array where all adds are preformed at the end of the sequence
A stack is a container that can be defined in terms of an array where all adds are preformed at the end of the sequence of existing values, and all removes are also preformed at the end of the sequence of existing values. An empty stack is one that has no existing values in the array at all. We use the notion of a top of the stack to keep track of (at which index) a new value in the sequence is to be added. Hence, an empty stack is one in which top = 0 and a full stack is one in which top = size
First, you are given the contents of the file stack.h (which may not be modified):
typedef unsigned int word;
// create an empty stack with capacity size
int* create_stack(const word size, word* top);
// add a new value to the top of the stack (if not full)
void add(int* stack, word* top, const word size, const int new_value);
// remove (and return) the value at the top of the stack (if not empty)
int rem(int* stack, word* top);
and the contents of the file main.c (which also may not be modified):
#include
#include
#include "stack.h"
int main(int args, char* argv[])
{
const word SIZE = 80;
int* my_stack = NULL;
word my_top;
my_stack = create_stack(SIZE, &my_top);
int i;
for(i = 1; i < 10; ++i)
add(my_stack, &my_top, SIZE, 2 * i);
printf("top = %d ", my_top);
for(i = 1; i < 10; ++i)
printf("%d ", rem(my_stack, &my_top));
printf("top = %d ", my_top);
free(my_stack);
return 0;
}
You will need to create the files :
stack.c
Makefile
Such that when all the files are in one directory (in UNIX) typing
make
followed by
./main
Will produce the following output:
$ make
gcc -Wall -c stack.c
gcc -Wall -c main.c
gcc stack.o main.o -o main
$ ./main
top = 9
18
16
14
12
10
8
6
4
2
top = 0
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
