Skip to content

Instantly share code, notes, and snippets.

@thedouglenz
Last active August 29, 2015 14:17
Show Gist options
  • Save thedouglenz/0ca59054a2215ffd2103 to your computer and use it in GitHub Desktop.
Save thedouglenz/0ca59054a2215ffd2103 to your computer and use it in GitHub Desktop.
Working with linked lists in C
/*
*
* A program that takes a list of numbers as arguments
* and turns them into the payload for a set of nodes
* that become a linked list, linked in the order
* the numbers are given to the program.
*
* Douglas Lenz, 2015
*
*/
#include <stdlib.h>
#include <stdio.h>
struct Node {
int value;
struct Node* next;
};
struct Node* makeNodeAndReturnAddress() {
return malloc(sizeof(struct Node));
}
void traverseLinkedList(struct Node* root, int length) {
int i;
struct Node* walker = root;
for(i=0; i < length; i++) {
if(i != 0)
printf("---->");
printf("[%d]", walker->value);
walker = walker->next;
}
printf("\n");
}
int main(int argc, char *argv[]) {
int i, size, *value;
struct Node * head = NULL, * lastNode = NULL;
// Parse command line args to make an array of the values
if(argc == 1) {
printf("Usage: %s number [number ...]", argv[0]);
return 0;
} else {
size = argc - 1;
value = (int *)malloc(size * sizeof(int));
for(i=0; i < size; i++) {
value[i] = strtol(argv[i+1], NULL, 0);
}
}
// Construct a linked list of the values
for(i=0; i < size; i++) {
struct Node* newNode = makeNodeAndReturnAddress();
newNode->value = value[i];
if(lastNode != NULL)
lastNode->next = newNode;
else
head = newNode;
lastNode = newNode;
}
// Traverse the linked list and print it's values
traverseLinkedList(head, size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment