Created
November 28, 2025 18:25
-
-
Save mgabrielmarin/c94fc33930310e4a221ba1fa20bab24d to your computer and use it in GitHub Desktop.
Stack implementation using linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Stack implemetation using linked list */ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| struct node { | |
| int data; | |
| struct node *next; | |
| }; | |
| struct node *createNode(int data) { | |
| struct node *n = malloc(sizeof(struct node)); | |
| if (n == NULL) { | |
| printf("Failed to create node.\n"); | |
| return NULL; | |
| } | |
| n->data = data; | |
| n->next = NULL; | |
| return n; | |
| } | |
| struct stack { | |
| struct node *top; | |
| }; | |
| struct stack *createStack() { | |
| struct stack *s = malloc(sizeof(struct stack)); | |
| if (s == NULL) { | |
| printf("Failed to create stack.\n"); | |
| return NULL; | |
| } | |
| return s; | |
| } | |
| int isEmpty(struct stack *s) { | |
| return (s->top == NULL) ? 1 : 0; | |
| } | |
| void push(struct stack *s, int data) { | |
| struct node *n = createNode(data); | |
| n->next = s->top; | |
| s->top = n; | |
| } | |
| int pop(struct stack *s) { | |
| if (isEmpty(s)) return 0; | |
| struct node *n = s->top; | |
| int data = n->data; | |
| s->top = s->top->next; | |
| free(n); | |
| return data; | |
| } | |
| int peek(struct stack *s) { | |
| if (isEmpty(s)) return 0; | |
| return s->top->data; | |
| } | |
| void printStack(struct stack *s) { | |
| struct node *n = s->top; | |
| while (n) { | |
| printf("%d ", n->data); | |
| n = n->next; | |
| } | |
| printf("\n"); | |
| } | |
| int main(void) { | |
| struct stack *s = createStack(); | |
| push(s, 3); | |
| push(s, 30); | |
| push(s, 10); | |
| printStack(s); | |
| printf("peek() = %d\n", peek(s)); | |
| printStack(s); | |
| printf("pop() = %d\n", pop(s)); | |
| printStack(s); | |
| free(s); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment