I am trying to create a program that implements a stack in C.
Currently, my stack is showing up empty.
I think this is because I pass the stack but not a pointer to the stack.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int info;
struct node * ptr;
}node;
//create
//push
//pop
//destroy
//display
void push(int, node * top_node);
void pop(node * top_node);
void destroy(node * top_node);
void display(node * top_node);
int main(int argc, char** argv)
{
node * top_node = NULL;
push(1, top_node);
push(5, top_node);
push(55, top_node);
display(top_node);
pop(top_node);
display(top_node);
pop(top_node);
display(top_node);
pop(top_node);
display(top_node);
push(1, top_node);
display(top_node);
destroy(top_node);
return (EXIT_SUCCESS);
}
void display(node * top_node)
{
node * temp = top_node;
if(top_node == NULL)
{
printf("The stack is empty\n");
return;
}
while(temp != NULL)
{
printf("%d\n ", temp-> info);
temp = top_node -> ptr;
}
}
void push(int data, node * top_node)
{
if(top_node == NULL)
{
top_node = (struct node **) malloc(1*sizeof(struct node));
top_node ->ptr = NULL;
top_node -> info = data;
}
else
{
node * temp = (struct node *) malloc(1*sizeof(struct node));
temp -> ptr = top_node;
temp -> info = data;
top_node = &temp;
}
}
void pop(node * top_node)
{
node * new_top = top_node;
if(new_top == NULL)
{
printf("\nERROR, the stack is empty");
return;
}
else
{
new_top = new_top -> ptr;
printf("popped value = %d", top_node -> info);
free(top_node);
top_node = new_top;
}
}
void destroy(node * top_node)
{
node * temp = top_node;
while(temp != NULL)
{
temp = top_node -> ptr;
free(top_node);
top_node = temp;
temp = temp->ptr;
}
free(temp);
}
The output that I am getting is this:
The stack is empty
ERROR, the stack is emptyThe stack is empty
ERROR, the stack is emptyThe stack is empty
ERROR, the stack is emptyThe stack is empty
The stack is empty
RUN SUCCESSFUL (total time: 227ms)
I believe that I should pass a pointer to stack, I tried implementing it but it shot out a bunch of errors.
Any step in the direction without giving me the full answer would be greatly appreciated.