Need a little help with printing a stack
Hello, I've been learning stack ADT from one of the books and I've written the following stack programs which works fine if the "print(stack)" is called after "popStack(stack)."
However if I call "print(stack)" before "popStack(stack)", something goes wrong. Could you please help, below is the code for the same.
Thanks in advance.
Code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
void *dataPtr;
struct node *link;
}STACK_NODE;
typedef struct
{
int count;
STACK_NODE *top;
}STACK;
STACK *createStack(void)
{
STACK *stack;
stack = (STACK *)malloc(sizeof(STACK));
if(stack)
{
printf("Stack created successfully. . .");
stack->count = 0;
stack->top = NULL;
}
return stack;
}
void pushStack(STACK *stack, void *dataInPtr)
{
STACK_NODE *newNode;
if(newNode = (STACK_NODE *)malloc(sizeof(STACK_NODE)))
{
printf("\n\n%d pushed onto Stack successfully.", (int *)dataInPtr);
newNode->dataPtr = dataInPtr;
newNode->link = stack->top;
stack->top = newNode;
(stack->count)++;
}
}
void print(STACK *stack)
{
STACK *temp;
temp = stack;
printf("\n\n");
while(temp->top != NULL)
{
printf("%d\n", temp->top->dataPtr);
temp->top = temp->top->link;
}
free(temp);
}
void *popStack(STACK *stack)
{
STACK_NODE *temp;
void *dataOutPtr;
if(stack->count == 0)
dataOutPtr = NULL;
else
{
temp = stack->top;
dataOutPtr = stack->top->dataPtr;
stack->top = stack->top->link;
(stack->count)--;
free(temp);
}
return dataOutPtr;
}
int main(void)
{
STACK *stack;
stack = createStack();
pushStack(stack, 10);
pushStack(stack, 20);
//print(stack);
printf("\n\nElement popped is %d", (int *)popStack(stack));
print(stack);
getch();
return 0;
}