|
| 1 | +#include<stdio.h> |
| 2 | +#include<stdlib.h> |
| 3 | + |
| 4 | + |
| 5 | +typedef struct Node |
| 6 | +{ |
| 7 | + int data; |
| 8 | + struct Node *next; |
| 9 | +} node; |
| 10 | + |
| 11 | + |
| 12 | +typedef struct Pop_Node |
| 13 | +{ |
| 14 | + int data; |
| 15 | + int returned; |
| 16 | +} pop_node; |
| 17 | + |
| 18 | + |
| 19 | +int push(node *stack, int data) |
| 20 | +{ |
| 21 | + node *temp=(node*)malloc(sizeof(node)); |
| 22 | + temp->data=data; |
| 23 | + temp->next=stack->next; |
| 24 | + |
| 25 | + stack->next=temp; |
| 26 | + return stack->next->data; |
| 27 | +} |
| 28 | + |
| 29 | + |
| 30 | +pop_node* pop(node *stack) |
| 31 | +{ |
| 32 | + pop_node *res=(pop_node*)malloc(sizeof(pop_node)); |
| 33 | + res->returned=0; |
| 34 | + |
| 35 | + node *temp; |
| 36 | + |
| 37 | + if(stack->next == NULL) |
| 38 | + { |
| 39 | + return res; |
| 40 | + } |
| 41 | + |
| 42 | + temp=stack->next; |
| 43 | + res->data=stack->next->data; |
| 44 | + res->returned=1; |
| 45 | + stack->next=stack->next->next; |
| 46 | + free(temp); |
| 47 | + |
| 48 | + return res; |
| 49 | +} |
| 50 | + |
| 51 | + |
| 52 | +void display(node *stack) |
| 53 | +{ |
| 54 | + printf("\nDisplay of the Stack\n"); |
| 55 | + |
| 56 | + if(stack->next == NULL) |
| 57 | + { |
| 58 | + printf("The Stack is empty\n"); |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + while(stack->next != NULL) |
| 63 | + { |
| 64 | + printf("%d", stack->next->data); |
| 65 | + |
| 66 | + if(stack->next->next != NULL) |
| 67 | + { |
| 68 | + printf(" <= "); |
| 69 | + } |
| 70 | + |
| 71 | + stack=stack->next; |
| 72 | + } |
| 73 | + printf("\n"); |
| 74 | +} |
| 75 | + |
| 76 | + |
| 77 | +int main() |
| 78 | +{ |
| 79 | + int n, i, data, pushed; |
| 80 | + |
| 81 | + node *stack=(node*)malloc(sizeof(node)); |
| 82 | + stack->next=NULL; |
| 83 | + |
| 84 | + printf("Enter the initial size of the Stack: "); |
| 85 | + scanf("%d", &n); |
| 86 | + |
| 87 | + printf("\nPush %d data to the Stack: \n", n); |
| 88 | + for(i=0; i<n; i++) |
| 89 | + { |
| 90 | + scanf("%d", &data); |
| 91 | + pushed=push(stack, data); |
| 92 | + |
| 93 | + printf("%d pushed to the Stack\n", pushed); |
| 94 | + } |
| 95 | + |
| 96 | + display(stack); |
| 97 | + |
| 98 | + printf("\nPopping data from the Stack: "); |
| 99 | + pop_node *popped; |
| 100 | + popped=pop(stack); |
| 101 | + |
| 102 | + if(popped->returned == 1) |
| 103 | + { |
| 104 | + printf("\n%d popped from the Stack\n", popped->data); |
| 105 | + } |
| 106 | + else |
| 107 | + { |
| 108 | + printf("\nNothing to pop, the Stack is empty\n"); |
| 109 | + } |
| 110 | + |
| 111 | + display(stack); |
| 112 | + |
| 113 | + printf("\nPush data to the Stack: "); |
| 114 | + scanf("%d", &data); |
| 115 | + pushed=push(stack, data); |
| 116 | + printf("%d pushed to the Stack\n", pushed); |
| 117 | + |
| 118 | + display(stack); |
| 119 | + |
| 120 | + return 0; |
| 121 | +} |
0 commit comments