void push(int data, Quack qs) { if (qs == NULL) { fprintf(stderr, "push: quack not initialised\n"); } else { Quack newnode; newnode = (Quack)malloc(sizeof(struct _node)); assert(newnode != NULL); newnode->data = data; newnode->next = qs->next; qs->next = newnode; } } |
In the tutorial last week, we saw that we can insert a node in a linked list using either insertHead() or insertTail(), corresponding to an insert at the start or end of the linked list.
NodeT *??????(NodeT *head, int data) { NodeT *new; new = (NodeT *)malloc(sizeof(NodeT)); assert(new != NULL); new->data = data; new->next = head; return new; } |
Complementary to the (linked-list) push operation, we have the (linked-list) pop operation:
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 } |
In the array implementation of a quack we used the struct:
#define HEIGHT 1000 struct _node { int array[HEIGHT]; int top; }; |
In createQuack() a struct _node is malloc'd. Assume the node is called qs. The variable top in this struct gets initialised as follows:
qs->top = -1; |