summaryrefslogtreecommitdiff
path: root/stack.c
diff options
context:
space:
mode:
authorMichael Hunteman <michael@huntm.net>2023-09-23 12:53:46 -0500
committerMichael Hunteman <michael@huntm.net>2023-10-21 21:48:03 -0500
commit9891f38ddcca971fa21ab61e7a70832c8c877b0a (patch)
tree1e820435b42c5c8187bb6d17b3ff1c204c933c1a /stack.c
Initial commitHEADmaster
Diffstat (limited to 'stack.c')
-rw-r--r--stack.c63
1 files changed, 63 insertions, 0 deletions
diff --git a/stack.c b/stack.c
new file mode 100644
index 0000000..a460629
--- /dev/null
+++ b/stack.c
@@ -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;
+}