Skip to content

Instantly share code, notes, and snippets.

@kenchangh
Created March 5, 2015 11:11
Show Gist options
  • Save kenchangh/506942d55d363da5c59c to your computer and use it in GitHub Desktop.
Save kenchangh/506942d55d363da5c59c to your computer and use it in GitHub Desktop.
An implementation for linked list in C. Just to polish up my C skills.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int value;
struct node *next;
} node;
node *add_item(node *head, int value) {
node *new_node = malloc(sizeof(node));
if (head != NULL) {
head->next = new_node;
}
new_node->value = value;
new_node->next = malloc(sizeof(node));
return new_node;
}
int get_index(node *start, int index) {
int value;
int i = 0;
node *current_node = start; // first node is current
while (1) {
if (i == index) {
return current_node->value; // return the value when index matches, breaks out from loop
} else {
// make next node the current_node
current_node = current_node->next;
}
i++;
}
}
int main() {
node *head, *start;
start = head = add_item(NULL, 1);
printf("%i\n", head->value); // 1
head = add_item(head, 2);
printf("%i\n", head->value); // 2
head = add_item(head, 3);
printf("%i\n", head->value); // 3
printf("%i\n", get_index(start, 0)); // 1
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment