#include<stdio.h>
#include<stdlib.h>
#include"list.h"
void list_init(list_t *l){
l->head.next = &l->tail;
l->head.prev = NULL;
l->tail.next = NULL;
l->tail.prev = &l->head;
l->head.data = 0;
l->tail.data = 0;
}
void list_deinit(list_t *l){
while (l->head.next != &l->tail){
node_t* first = &l->head;
node_t* mid = first->next;
node_t* last = mid->next;
free(mid);
first->next = last;
last->prev = first;
}
}
void list_add_head(list_t *l, int data){
node_t* new = malloc(sizeof(node_t));
new->data = data;
new->next = NULL;
new->prev = NULL;
node_t* mid = l->head.next;
l->head.next = new;
new->next = mid;
new->prev = &l->head;
mid->prev = new;
}
void list_add_tail(list_t *l, int data){
node_t* new = malloc(sizeof(node_t));
new->data = data;
new->next = NULL;
new->prev = NULL;
node_t* mid = l->tail.prev;
l->tail.prev = new;
new->prev = mid;
new->next = &l->tail;
mid->next = new;
}
void list_add(list_t *l, int data){
node_t* new = malloc(sizeof(node_t));
new->data = data;
new->next = NULL;
new->prev = NULL;
for(node_t* p = &l->head;p != &l->tail;p = p->next) {
node_t* first = p;
node_t* mid = first->next;
if((new->data < mid->data) || (mid == &l->tail)){
first->next = new;
new->next = mid;
new->prev = first;
mid->prev = new;
break;
}
}
}
void list_del(list_t *l, int data){
for(node_t* p = &l->head;p != &l->tail;p = p->next) {
node_t* first = p;
node_t* mid = first->next;
node_t* last = mid->next;
if (mid->data == data) {
free(mid);
first->next = last;
last->prev = first;
break;
}
}
}
void list_travel(list_t *l){
for (node_t* p = l->head.next;p != &l->tail;p = p->next) {
printf("%d\n",p->data);
}
}