Skip to content

Instantly share code, notes, and snippets.

@jez
Created October 8, 2015 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jez/24a29fd17b2eecf39e04 to your computer and use it in GitHub Desktop.
Save jez/24a29fd17b2eecf39e04 to your computer and use it in GitHub Desktop.
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