题目链接双向链表
这道题一开始没有灵感,于是网上搜了下答案.没搜到.于是只好自己乖乖的慢慢改bug.发现List表的head表头和tail表尾是都不为空的,都是指向了具体的节点的,而且这是一个双向循环链表,结尾的遍历和释放都明显错了.代码贴在下面啦:
list.c
#include "list.h"
struct List*
init_list () {
struct List* list = (struct List *) malloc (sizeof (struct List));
list->head = list->tail = NULL;
return list;
}
void
free_list (struct List* list) {
struct Node* current = list->head;
struct Node* pcurrent = current;
current = current->next;
free(pcurrent);
while (current != list->head) {
pcurrent = current;
current = current->next;
free (pcurrent);
}
free (list);
}
void
traverse_list (struct List* list, void (*callback)(void* data)) {
struct Node* current = list->head;
while (current) {
(*callback)(current->data);
current = current->next;
if(current == list->head)
break;
}
}
void
insert_after (struct List* list, struct Node* prev, void* data) {
struct Node* next = prev ? prev->next : list->head;
struct Node* newnode = (struct Node *) malloc (sizeof (struct Node));
newnode->data = data;
newnode->prev = prev ? prev : list->tail;
newnode->next = next;
prev ? prev->next = newnode : list->tail ? list->tail->next = newnode : NULL;
next ? next->prev = newnode : 0 ;
list->head == NULL ? list->head = list->tail = newnode :
prev == NULL ? list->tail = newnode : 0 ;
}
void
insert_before (struct List* list, struct Node* next, void* data) {
struct Node* prev = next ? next->prev : list->tail;
struct Node* newnode = (struct Node *) malloc (sizeof (struct Node));
newnode->data = data;
newnode->prev = prev;
newnode->next = next ? next : list->head;
next ? next->prev = newnode : list->head ? list->head->prev = newnode : NULL;
prev ? prev->next = newnode : 0 ;
list->tail == NULL ? list->head = list->tail = newnode :
next == NULL ? list->head = newnode : 0 ;
}
void
insert_front (struct List* list, void* data) {
insert_before (list, NULL, data);
}
void
insert_back (struct List* list, void* data) {
insert_after (list, NULL, data);
}
void
delete_from (struct List* list, struct Node* node) {
struct Node* prev = node->prev;
struct Node* next = node->next;
prev ? prev->next = next : 0 ;
next ? next->prev = prev : 0 ;
node == list->head ? list->head = next : 0;
node == list->tail ? list->tail = prev : 0;
free (node);
}
其余两个文件不用改动
实现效果: