add my unfinished cbase
This commit is contained in:
parent
501065651d
commit
bb63a9dd3c
16 changed files with 277 additions and 0 deletions
116
cbase/data/lists/linkedlist.c
Normal file
116
cbase/data/lists/linkedlist.c
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
#include <stdlib.h>
|
||||
|
||||
#include "linkedlist.h"
|
||||
|
||||
LinkedList*
|
||||
new_linkedlist() {
|
||||
// TODO: handle malloc failure
|
||||
LinkedListNode* nil = malloc(sizeof(LinkedListNode));
|
||||
nil->next = nil;
|
||||
nil->prev = nil;
|
||||
|
||||
LinkedList* l = malloc(sizeof(LinkedList));
|
||||
l->nil = nil;
|
||||
|
||||
return l;
|
||||
}
|
||||
|
||||
LinkedListNode*
|
||||
first(LinkedList* l) {
|
||||
return l->nil->next;
|
||||
}
|
||||
|
||||
LinkedListNode*
|
||||
last(LinkedList* l) {
|
||||
return l->nil->prev;
|
||||
}
|
||||
|
||||
void
|
||||
append(LinkedList* l, void* x) {
|
||||
LinkedListNode* nil = l->nil;
|
||||
|
||||
// TODO: handle malloc failure
|
||||
LinkedListNode* y = malloc(sizeof(LinkedListNode));
|
||||
y->next = nil;
|
||||
y->prev = nil->prev->prev;
|
||||
y->data = x;
|
||||
|
||||
nil->prev->prev->next = y;
|
||||
nil->prev = y;
|
||||
}
|
||||
|
||||
void
|
||||
insert(LinkedList* l, void* x) {
|
||||
LinkedListNode* nil = l->nil;
|
||||
|
||||
// TODO: handle malloc failure
|
||||
LinkedListNode* y = malloc(sizeof(LinkedListNode));
|
||||
y->prev = nil;
|
||||
y->next = nil->next;
|
||||
y->data = x;
|
||||
|
||||
nil->next->prev = x;
|
||||
nil->next = x;
|
||||
}
|
||||
|
||||
void
|
||||
insert_at(LinkedList* l, int at, void* x) {
|
||||
LinkedListNode* nil = l->nil;
|
||||
LinkedListNode* y = nil;
|
||||
|
||||
for (int i = 0; i < at; i++) {
|
||||
y = y->next;
|
||||
if (y == nil) {
|
||||
// Index out of range
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: handle malloc failure
|
||||
LinkedListNode* new = malloc(sizeof(LinkedListNode));
|
||||
new->prev = y;
|
||||
new->next = y->next;
|
||||
new->data = x;
|
||||
|
||||
y->next->prev = new;
|
||||
y->next = new;
|
||||
}
|
||||
|
||||
LinkedListNode*
|
||||
search(LinkedList* l, void* x) {
|
||||
LinkedListNode* y = l->nil->next;
|
||||
|
||||
while (y != l->nil) {
|
||||
if (y->data == x)
|
||||
return y;
|
||||
y = y->next;
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void
|
||||
delete_item(LinkedListNode* x) {
|
||||
x->prev->next = x->next;
|
||||
x->next->prev = x->prev;
|
||||
|
||||
free(x);
|
||||
}
|
||||
|
||||
void
|
||||
delete_linkedlist(LinkedList* l) {
|
||||
free(l->nil);
|
||||
free(l);
|
||||
}
|
||||
|
||||
int
|
||||
count_linkedlist(LinkedList* l) {
|
||||
int n = 0;
|
||||
LinkedListNode* x = l->nil;
|
||||
|
||||
while (x->next != l->nil) {
|
||||
x = x->next;
|
||||
n++;
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue