#include "quack.h" ... Quack q = NULL; q = createQuack(); push(1, q); pop(q); |
If the push operation returned a new head, then we would need to call push() as:
q = push(1, q); // this is not so attractive |
1 int pop(Quack qs) { 2 int retval = 0; 3 if (qs == NULL) { 4 fprintf(stderr, "pop: quack not initialised\n"); 5 } else { 6 if (isEmptyQuack(qs)) { 7 fprintf(stderr, "pop: quack underflow\n"); 8 } else { 9 Quack topnode = qs->next; // top node must be there 10 retval = topnode->data; 11 qs->next = topnode->next; 12 free(topnode); 13 } 14 } 15 return retval; 16 } |
if qs has been created ... and qs is not empty ... let topnode point to the second node in the linked list store the data from topnode remove topnode by relinking to topnode's next node free topnode return the data from topnode |
++(qs->top); // we are adding an element, so increment the index qs->array[qs->top] = data; // place the element at this location |
if (qs->top >= HEIGHT-1) { fprintf(stderr, "push: quack overflow\n"); } |
data = qs->array[qs->top]; // 'get' the top element on the quack --(qs->top); // decrement the index indicating the top of quack return data; // return the top element |
to check for quack underflow:
if (qs->top <= -1) { fprintf(stderr, "pop: quack underflow\n"); } |