Jack is Back
Suppose that a stack
for numbers is declared in C, per the below:
const int CAPACITY = 50;
typedef struct
{
int numbers[CAPACITY];
int size;
}
stack;
Suppose, too, that one such stack
, s
, has been defined globally, per the below:
stack s;
And that it’s been initialized in main
, per the below:
s.size = 0;
Recall that “push” means to add a number to the “top” of s
.
-
(3 points.) In
test/jack/push.c
, complete the implementation ofpush
, below, in such a way that the function pushesn
ontos
, returningtrue
if successful. If the stack is already full, the function should instead returnfalse
.bool push(int n) { // TODO }
Recall that “pop” means to remove and return the “top” (i.e., most recently pushed) number from s
. Consider the incomplete implementation of pop
, below. It, too, is meant to return true
if successful and false
if not.
bool pop(int *n)
{
// TODO
}
-
(2 points.) In no more than two sentences, when should
pop
returnfalse
? -
(2 points.) Why does
pop
take the address of anint
as its argument rather than an actualint
? -
(3 points.) In
test/jack/pop.c
, complete the implementation ofpop
, above, in such a way that the function pops the top number froms
.
Suppose that a stack
is instead declared per the below:
typedef struct
{
int *numbers;
int size;
}
stack;
And suppose that one such stack
, t
, has been defined globally, per the below:
stack t;
And that it’s been initialized in main
, per the below:
t.numbers = NULL;
t.size = 0;
-
(3 points.) In
test/jack/push2.c
, complete the re-implementation ofpush
, below, in such a way that the function pushesn
ontot
, returningtrue
if successful, allocating more memory fort.numbers
as needed. If sufficient memory cannot be allocated, the function should instead returnfalse
.bool push(int n) { // TODO }