ACPbE, Chpt3.2, ex3.6,Stacks and Queues

Run Settings
LanguageC
Language Version
Run Command
#include <stdio.h> #include <stdlib.h> // malloc() and exit() #define EMPTY NULL typedef struct node NODE; struct node { int i; struct node *next; }; // Stack Push() NODE *pushs (NODE *stack, int i) { NODE *new ; if ((new = (NODE *) malloc( sizeof(NODE))) == NULL) { printf ("errFATAL, malloc() in pushs!\n"); exit (1); } new->i = i ; new->next = stack ; stack = new ; return stack ; } NODE *pops( NODE **stack) { NODE *first; if (*stack == NULL) return NULL; first = *stack ; *stack = (*stack)->next; first->next = NULL ; return first; } // Queue push void pushq (NODE **q, NODE **rear, int i) { NODE *new ; if ((new = (NODE *)malloc(sizeof(NODE))) == NULL) { printf ("errFATAL, malloc in pushq()\n"); exit (1); } new->i = i ; new->next = NULL ; if (*q == NULL) *q = new ; // no q add item else (*rear)->next = new ; // update (*rear)->next, queue *rear = new ; } NODE *popq (NODE **q, NODE **rear) { NODE *first ; first = *q ; if (*q == NULL) return NULL ; //empty Q, nothing to pop *q = (*q)->next ; if (*q == NULL) *rear = NULL; first->next = NULL ; return first ; } // driver program for stack and queue int main(void) { NODE *stack = NULL, *q = NULL, *rear = NULL, *top; NODE *pushs (NODE *stack, int i), *pops(NODE **stack), *popq (NODE **q, NODE **rear); void pushq (NODE **q, NODE **rear, int i); // Begin stack testing stack = pushs (stack, 3) ; stack = pushs (stack, 4) ; stack = pushs (stack, 5) ; top = pops (&stack) ; printf ("Top node of stack is %d\n", top ? top->i : EMPTY ) ; top = pops (&stack) ; printf ("Top node of stack is %d\n", top ? top->i : EMPTY ) ; top = pops (&stack) ; printf ("Top node of stack is %d\n", top ? top->i : EMPTY ) ; // Beginning queue driver pushq (&q, &rear, 3) ; pushq (&q, &rear, 4) ; pushq (&q, &rear, 5) ; top = popq (&q, &rear) ; printf ("Top node of queue is %d\n", top ? top->i : EMPTY) ; top = popq (&q, &rear) ; printf ("Top node of queue is %d\n", top ? top->i : EMPTY) ; top = popq (&q, &rear) ; printf ("Top node of queue is %d\n", top ? top->i : EMPTY) ; top = popq (&q, &rear) ; printf ("Top node of queue is %d\n", top ? top->i : EMPTY) ; printf("Hello World!\n"); return 0; }
Editor Settings
Theme
Key bindings
Full width
Lines