staticintinsertDlist(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; return0; }
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; return0; } else { // in the middle node-> next = head -> next; head -> next -> pre = node; node -> pre = head; head -> next = node; return0; } }
staticintdeleteDlist(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; } return0; } 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; } } return0; }
本文所述是 C 语言实现的,源码 在 Go 语言之中, container/list 包实现了双链表,直接引入就可以使用了。