Skip to content

Instantly share code, notes, and snippets.

@jez jez/rev.c
Created Oct 8, 2015

Embed
What would you like to do?
Reverses a linked list
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
// --- stack library functions ---
// typedefs to keep things more semantic
typedef struct stack_s Stack;
typedef Stack node_t;
struct stack_s {
Stack* next;
int data;
};
// Create and delete the underlying datastructure
size_t count = 0;
Stack* init() {
Stack* stack = malloc(sizeof(Stack));
stack->next = NULL;
stack->data = count++;
return stack;
}
void deinit(Stack* stack) {
if (!stack) return;
node_t* next = stack->next;
free(stack);
deinit(next);
}
// Utility functions
bool is_empty(Stack** stack) {
return !(*stack)->next;
}
void print(Stack* stack) {
for (; stack && stack->next; stack = stack->next) {
printf("%d -> ", stack->data);
}
printf("X\n");
}
// Core stack operations
void push(Stack** stack, node_t* node) {
node->next = *stack;
*stack = node;
}
Stack* pop(Stack** stack) {
if (is_empty(stack)) return NULL;
node_t* result = *stack;
*stack = (*stack)->next;
return result;
}
void rev(Stack** stack) {
Stack* temp = init();
while (!is_empty(stack)) {
push(&temp, pop(stack));
}
deinit(*stack);
*stack = temp;
}
// --- tests ---
int main() {
Stack* stack = init();
push(&stack, init());
push(&stack, init());
push(&stack, init());
print(stack);
rev(&stack);
print(stack);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.