I am no where near a good programmer and I am just trying to get throught this last assignment with some help. I have written some of the code but need help with the push and pull aspect. I need to complete the two functions: push and pop such that they correctly implement the operation of a queue. The code I have is as follows: (an example of what output I need is at the bottom) THANKS for your help! Code: #include <stdio.h> #include <stdlib.h> #include <time.h> struct node // element in a stack { int val; // value of element in node struct node * next; // pointer to next node }; typedef struct node item; void print( item * ); item* push ( item *, int ); int pop ( item ** ); int main() { item * stack = NULL; // initialize first node int i; // initialize random number generator//////////////////////////// srand(time(NULL)); // push random values to stack ////////////////////////////////// for(i=1;i<=4;i++) { int v = rand()%10 ; stack = push( stack, v); print( stack ); } // pop stack ////////////////////////////////////////////////////// for(i=1; i <= 5; i++ ) { printf("Pop returns %d\n", pop(&stack) ); } system("pause"); return 0; } item* push ( item * head , int value ) { printf("Push %d\n", value); return NULL; } int pop ( item ** head ) // removes top element from stack // if stack is empty, return -99 // returns value of top element from stack { cout << "Popping 4 elements " << endl; for (int i = 0; i < 4; ++i) { cout << s.top() << endl; s.pop(); return -99; } void print( item * start ) { if ( start == NULL ) printf("End of stack ************ \n"); else { printf("addr:%8d val:%3d next:%8d\n", start, start->val,start->next); print( start->next); } } Sample output Push 0 addr: 3346344 val: 0 next: 0 End of stack ************ Push 7 addr: 3346448 val: 7 next: 3346344 addr: 3346344 val: 0 next: 0 End of stack ************ Push 1 addr: 3346464 val: 1 next: 3346448 addr: 3346448 val: 7 next: 3346344 addr: 3346344 val: 0 next: 0 End of stack ************ Push 6 addr: 3346480 val: 6 next: 3346464 addr: 3346464 val: 1 next: 3346448 addr: 3346448 val: 7 next: 3346344 addr: 3346344 val: 0 next: 0 End of stack ************ Pop returns 6 Pop returns 1 Pop returns 7 Pop returns 0 Pop returns -99 Press any key to continue . . .
It is not a good idea to use typedef when you make a linked list. Better with a struct. Could“t find your stack struct. You need to have: Code: struct node { int x; struct node*next; }; struct stack { struct node*head; }; void push(struct stack *s,int x) { struct node*new; new=malloc(sizeof(struct node)); new->x=val; new->next=s->head; s->head=new; } int pop(struct stack *s) { int x; if(s->head!=NULL) { tal=s->head->x; struct node*e=s->head; s->head=s->head->next; free(e); return x; } return 0; }