1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include<stdio.h> #include<stdlib.h>
typedef struct node{ int data; struct node *next; }node;
int push(node *top, int data); int pop(node *top); node* stack_init(); void display(node *current);
int push(node *top, int data){ node *temp = (node *)malloc(sizeof(node)); temp->data = data; temp->next = top->next; top->next = temp;
return data; }
int pop(node *top){ if(!top->next){ printf("Stack is empty now."); return -1; } int pop_data = top->next->data; node *temp = top->next; top->next = top->next->next; temp = NULL; free(temp);
return pop_data; }
node* stack_init(){ node *temp = (node *)malloc(sizeof(node)); temp->data = 0; temp->next = NULL;
return temp; }
void display(node *current){ current = current->next; while(current){ printf("%d\n",current->data); current = current->next; } }
int main(){ int first_input; int pop_input, pop_data; node *top = stack_init(); int status;
printf("Enter strings, Ctrl+Z to quit.\n"); status = scanf("%d",&first_input); while(status!=EOF){ push(top, first_input); status = scanf("%d",&first_input); } display(top);
printf("Now enter 1 to pop data, 0 to quit.\n"); scanf("%d",&pop_input); while(pop_input==1){ pop_data = pop(top); if(pop_data==-1){ break; } printf("pop_data: %d\n",pop_data); scanf("%d",&pop_input); }
printf("\nDone\n");
return 0; }
|