Skip to content

Instantly share code, notes, and snippets.

@dkinzer
Last active August 29, 2015 14:21
Show Gist options
  • Save dkinzer/c99ad45279b596e1c994 to your computer and use it in GitHub Desktop.
Save dkinzer/c99ad45279b596e1c994 to your computer and use it in GitHub Desktop.
Playing around with linked lists in c.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
typedef struct node {
int value;
struct node * next;
} node;
struct node* make_node(int n);
int append(int n, struct node* list);
int prepend(int n, struct node** head);
int pop(struct node** head);
int insert(int n, int pos, struct node** head);
int push(int n, struct node* head);
void free_list(struct node* list);
void print_list(struct node* head);
int main (void) {
int error = 0;
node* head = make_node(0);
for (int i = 1; i < 2; i++) {
prepend(i, &head);
}
int value = 0;
print_list(head);
while (value != INT_MAX)
{
value = pop(&head);
if (value != INT_MAX) {
printf("%d\n", value);
}
}
return error;
}
struct node* make_node(int n)
{
struct node* node = NULL;
node = malloc(sizeof(struct node));
if (node != NULL) {
node->value = n;
node->next = NULL;
return node;
}
return NULL;
}
int append(int n, struct node* head)
{
node* curr = head;
node* node = make_node(n);
if (node == NULL) {
return 1;
}
while(curr->next != NULL) {
curr = curr->next;
}
curr->next = node;
return 0;
}
int prepend(int n, struct node** head)
{
if (head == NULL)
{
return INT_MAX;
}
node* node = make_node(n);
if (node == NULL) {
return INT_MAX;
}
node->next = (*head)->next;
(*head)->next = node;
return 0;
}
int insert(int n, int pos, struct node** head)
{
node* curr = *head;
node* node = make_node(n);
if (node == NULL) {
return 1;
}
for (int i = 0; i <= pos; i++) {
if (i == pos) {
if (curr->next == NULL) {
curr->next = node;
} else {
node->next = curr->next;
curr->next = node;
}
}
if (curr->next == NULL) {
return 2;
}
}
return 0;
}
int pop(struct node** head)
{
if (*head == NULL) {
free(*head);
return INT_MAX;
}
int value = (*head)->value;
node* curr = NULL;
curr = *head;
*head = (*head)->next;
free(curr);
return value;
}
void free_list(struct node* head)
{
node* curr = head;
node* next = NULL;
do {
next = curr;
curr = curr->next;
free(next);
} while (curr->next != NULL);
free(curr);
}
void print_list(struct node* head)
{
node* curr = head;
do {
printf("%d\n", curr->value);
if (curr->next != NULL) {
curr = curr->next;
}
else {
break;
}
} while (true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment