just was experimenting.. here is the code:
Code:
#include <stdlib.h>
#include <stdio.h>
#define snapd(arg) printf(#arg " = %d\n", arg);
#define snapf(arg) printf(#arg " = %f\n", arg);
struct fifo
{
int data;
struct fifo *next;
};
struct fifo *push(struct fifo *st, int value)
{
struct fifo *newnode;
if (st == NULL)
{
newnode = (struct fifo *)malloc(sizeof(struct fifo));
newnode->data = value;
newnode->next = NULL;
return newnode;
}
newnode = (struct fifo *)malloc(sizeof(struct fifo));
newnode->data = value;
newnode->next = st;
return newnode;
}
struct fifo *pop(struct fifo *st)
{
struct fifo *top;
if (st == NULL)
{
printf("The stack is empty!\n");
return NULL;
}
top = st->next;
free(st);
return top;
}
void printstack(struct fifo *st)
{
if (st == NULL)
{
printf("The stack is empty!\n");
return;
}
do
{
printf("%d\n", st->data);
st = st->next;
}
while (st);
}
int main (int argc, char *argv[])
{
struct fifo *myfifo = NULL;
int command, value;
printf("FIFO/Stack implementation with linked list.\n");
printf("1 - push value.\n");
printf("2 - pop value.\n");
printf("3 - print stack.\n");
printf("4 - exit.\n");
printf("Enter your command: ");
for (;;)
{
scanf("%d", &command);
switch (command)
{
case 1:
{
printf("Enter the value to push on to the stack: ");
scanf("%d",&value);
myfifo = push(myfifo, value);
printf("Enter the next command: ");
break;
}
case 2:
{
myfifo = pop(myfifo);
if (myfifo != NULL) printf("The value is popped out of the stack\n");
printf("Enter the next command: ");
break;
}
case 3:
{
printf("The contains of the stack is:\n");
printstack(myfifo);
printf("====================================\n");
printf("Enter the next command: ");
break;
}
case 4:
return 0;
default:
{
printf("Wrong command!\n");
printf("1 - push value.\n");
printf("2 - pop value.\n");
printf("3 - print stack.\n");
printf("4 - exit.\n");
printf("Enter your command: ");
break;
}
}
}