c_linked_list
Source: c_linked_list · updated 2024-08-19 · public gist
Synced verbatim from gist.github.com/bl9.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct Stack {
Node* head;
} Stack;
void push(Stack *stack, int val) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = val;
newNode->next = stack->head;
stack->head = newNode;
}
void pop(Stack *stack) {
Node *current = stack->head;
stack->head = current->next;
}
void printStack(Stack *stack) {
Node *current = stack->head;
while (current != NULL) {
printf("%d\n", current->data);
current = current->next;
}
}
void initStack(Stack *stack) { stack->head = NULL; }
int main() {
Stack s;
initStack(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
push(&s, 4);
printStack(&s);
pop(&s);
printf("------------\n");
printStack(&s);
printf("------------\n");
push(&s, 5);
printStack(&s);
return 0;
}