static int insertDlist(dlist **list, int num) {
Node * head = (*list) -> head;
Node * tail = (*list) -> tail;
if (list == NULL) return -1;
Node * node = initNode(num);
if (node == NULL) return -1;
// empty dlist
if ((*list) -> head == NULL && (*list) -> tail == NULL) {
(*list)-> head = node;
(*list)-> tail = node;
return 0;
}
while (head -> next && head -> num < num) {
head = head -> next;
}
// at the end
if (head->next == NULL) {
head -> next = node;
node -> pre = head;
tail -> pre = node;
return 0;
} else {
// in the middle
node-> next = head -> next;
head -> next -> pre = node;
node -> pre = head;
head -> next = node;
return 0;
}
}
static int deleteDlist(dlist ** list, int location) {
Node * head = (*list) -> head;
Node * now = NULL;
Node * last = NULL;
if (head == NULL)
return -1;
if (location <= 0 || location > numOfDlist(*list))
return -1;
if (location == 1) {
now = head;
(*list) -> head = now ->next;
head -> next ->pre = NULL;
if (now) {
free(now);
now = NULL;
}
return 0;
}
int num = 0;
while (head && num++ < location) {
head = head -> next;
}
if (head -> next == NULL) {
now = (*list) -> tail;
head -> pre -> next = NULL;
now -> pre = head->pre;
if (head) {
free(head);
head = NULL;
}
} else {
now = head -> next;
last = head -> pre;
now ->pre = head -> pre;
last -> next = head ->next;
if (head) {
free(head);
head = NULL;
}
}
return 0;
}
本文所述是 C 语言实现的,源码
在 Go 语言之中, container/list 包实现了双链表,直接引入就可以使用了。