Skip to content

Instantly share code, notes, and snippets.

@sidtronics
Created October 29, 2022 11:33
Show Gist options
  • Save sidtronics/fce2cc666ba6530d295edc58010b0ff1 to your computer and use it in GitHub Desktop.
Save sidtronics/fce2cc666ba6530d295edc58010b0ff1 to your computer and use it in GitHub Desktop.
Simple stack implementation using linked list in C.
#include<stdio.h>
#include<stdlib.h>
typedef struct Node Node;
struct Node{
int value;
Node* next;
};
struct Stack{
Node* last;
} stack = {NULL};
void Stack_push(int val);
void Stack_pop();
int main() {
Stack_push(0);
Stack_push(1);
Stack_push(2);
Stack_push(3);
Stack_push(4);
Stack_push(5);
while(stack.last != NULL) {
printf("%d\n", stack.last->value);
Stack_pop();
}
}
void Stack_push(int val) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->next = stack.last;
newNode->value = val;
stack.last = newNode;
}
void Stack_pop() {
Node* tmpNode = stack.last->next;
free(stack.last);
stack.last = tmpNode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment