Skip to content

Instantly share code, notes, and snippets.

@reagent
Last active December 13, 2015 23:19
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 reagent/4990923 to your computer and use it in GitHub Desktop.
Save reagent/4990923 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
typedef struct List {
Node *head;
int count;
} List;
Node *
node_create(int value)
{
Node *node = calloc(1, sizeof(Node));
node->value = value;
node->next = NULL;
return node;
}
List *
list_create()
{
List *list = calloc(1, sizeof(List));
list->head = NULL;
list->count = 0;
return list;
}
Node *
list_push(List *list, int value)
{
Node *cur = NULL,
*tail = NULL,
*new = node_create(value);
if (!list->head) {
// No elements in the list, just make this one the head.
list->head = new;
} else {
for (cur = list->head; cur != NULL; cur = cur->next) {
tail = cur;
}
tail->next = new;
}
list->count++;
return new;
}
void
list_print(List *list)
{
int i = 1;
Node *cur = NULL;
for (cur = list->head; cur != NULL; cur = cur->next) {
printf("Value of element #%d is: %d\n", i, cur->value);
i++;
}
printf("\n");
}
void
list_remove_value(List *list, int value)
{
Node *cur = list->head,
*prev = cur;
while (cur != NULL) {
if (cur->value == value) {
if (list->head == cur) {
list->head = cur->next;
} else {
prev->next = cur->next;
}
free(cur);
return;
}
prev = cur;
cur = cur->next;
}
}
int
list_sum(List *list)
{
int sum = 0;
Node *cur = NULL;
for (cur = list->head; cur != NULL; cur = cur->next) {
sum = sum + cur->value;
}
return sum;
}
void
list_free(List *list)
{
Node *current,
*next = list->head;
while (next != NULL) {
current = next;
next = current->next;
free(current);
};
free(list);
}
int
main()
{
List *list = list_create();
list_push(list, 1);
list_push(list, 2);
printf("Sum: %d\n", list_sum(list));
list_print(list);
list_remove_value(list, 1);
printf("Sum: %d\n", list_sum(list));
list_print(list);
list_free(list);
return 0;
}
CFLAGS=-g -Wall -Wextra
all: main
clean:
rm -rf main *.dSYM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment