Skip to content

Instantly share code, notes, and snippets.

@pmalek

pmalek/list.c

Last active May 6, 2016
Embed
What would you like to do?
single linked list in C
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
typedef struct node
{
int val;
struct node* next;
} node;
node* newNode(int val)
{
node* n = (node*)malloc(sizeof(node));
n->val = val;
n->next = NULL;
return n;
}
void printList(node* head)
{
if (head == NULL) return;
printf("%d", head->val);
while ((head = head->next)) {
printf(", %d", head->val);
}
printf("\n");
}
void clean(node* head)
{
while (head)
{
node* curr = head;
head = head->next;
free(curr);
}
}
void append(node** head, int val)
{
if(*head == NULL)
{
*head = newNode(val);
return;
}
node* curr = *head;
while (curr->next)
{
curr = curr->next;
}
curr->next = newNode(val);
}
void removeIf(node** head, int val)
{
node **curr = head;
while (*curr != NULL) {
if ((*curr)->val == val) {
node *next = (*curr)->next;
free(*curr);
*curr = next;
} else {
curr = &((*curr)->next);
}
}
}
int size(node* head)
{
int sz = 0;
while (head)
{
head = head->next;
++sz;
}
return sz;
}
void tests();
int main()
{
tests();
return 0;
}
/*
* Here are the tests for lists functionalities
*/
void tests()
{
{
node* root = newNode(1);
append(&root, 2);
assert(size(root) == 2);
clean(root);
}
{
node* root = newNode(1);
assert(size(root) == 1);
removeIf(&root, 1);
assert(size(root) == 0);
removeIf(&root, 1);
assert(size(root) == 0);
clean(root);
}
{
node* root = newNode(8);
append(&root, 2);
append(&root, 2);
assert(size(root) == 3);
clean(root);
}
{
node* root = newNode(8);
append(&root, 123);
append(&root, 123);
append(&root, 123);
append(&root, 123);
assert(size(root) == 5);
removeIf(&root, 123);
assert(size(root) == 1);
clean(root);
}
{
node* root = newNode(8);
append(&root, 123);
assert(size(root) == 2);
removeIf(&root, 1);
assert(size(root) == 2);
clean(root);
}
{
node* root = newNode(1);
append(&root, 1);
append(&root, 1);
append(&root, 1);
append(&root, 2);
append(&root, 3);
append(&root, 3);
append(&root, 4);
append(&root, 4);
append(&root, 5);
assert(size(root) == 10);
removeIf(&root, 1);
assert(size(root) == 6);
clean(root);
}
{
node* root = newNode(1);
append(&root, 1);
append(&root, 1);
append(&root, 1);
append(&root, 2);
append(&root, 3);
append(&root, 3);
append(&root, 4);
append(&root, 4);
append(&root, 5);
assert(size(root) == 10);
removeIf(&root, 3);
assert(size(root) == 8);
clean(root);
}
{
node* root = newNode(1);
append(&root, 1);
assert(size(root) == 2);
removeIf(&root, 1);
assert(size(root) == 0);
clean(root);
}
{
node* root = newNode(1);
append(&root, 1);
append(&root, 1);
append(&root, 1);
assert(size(root) == 4);
removeIf(&root, 1);
assert(size(root) == 0);
clean(root);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment