diff options
Diffstat (limited to 'stack.c')
-rw-r--r-- | stack.c | 63 |
1 files changed, 63 insertions, 0 deletions
@@ -0,0 +1,63 @@ +#include <stdio.h> +#include <stdlib.h> + +struct node { + int val; + struct node *prev; +}; + +struct node *head; + +void +push(int val) +{ + struct node *tmp = malloc(sizeof(struct node)); + tmp->val = val; + tmp->prev = head; + head = tmp; +} + +int +pop() +{ + if (head == NULL) { + return -1; + } + struct node *tmp = head; + int val = tmp->val; + head = head->prev; + free(tmp); + return val; +} + +int +peek() +{ + return head == NULL ? -1 : head->val; +} + +void +print() +{ + struct node *cur = head; + while (cur != NULL) { + printf("%d ", cur->val); + cur = cur->prev; + } + printf("\n"); +} + +int +main() +{ + int val, n = 0; + printf("How many integers?\n"); + scanf("%d", &n); + for (int i = 0; i < n; ++i) { + printf("Enter an integer \n"); + scanf("%d", &val); + push(val); + print(); + } + return 0; +} |