voiddeleteFront(LinkedList *list) { if (list->head == NULL) { return; // if the linked list is empty, do nothing } Node *tmp = list->head->next; // save the new head node free(list->head); list->head = tmp; }
注意检查列表是否为空!
删除链表末尾的节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
voiddeleteBack(LinkedList *list) { if (list->head == NULL) { // there is no node in linked list return; } if (list->head->next == NULL) { // there is only one node in linked list deleteFront(list); }
// find the second last node Node *current = list->head; while (current->next->next != NULL) { current = current->next; }
free(current->next); current->next = NULL; }
注意特殊判断链表为空和链表仅有一个元素的情况
删除链表所有的节点 (释放内存)
1 2 3 4 5 6 7 8 9 10
intdeleteAllNodes(LinkedList *list) { int numDeletedNodes = 0;
while (list->head != NULL) { deleteFront(list); numDeletedNodes++; }
booldeleteFirstMatch(LinkedList *list, int searchVal) { Node *current = list->head; if (current->data == searchVal) { deleteFront(list); returntrue; }
while (current->next != NULL && current->next->data != searchVal) { current = current->next; }
// current now points to a node just before the node that matched, // OR current points to the last node. if (current->next != NULL) { Node *tmp = current->next; current->next = tmp->next; free(tmp); returntrue; }
returnfalse; }
删除所有匹配的节点
1 2 3 4 5 6 7 8
intdeleteAllMatch(LinkedList *list, int searchVal) { int numDeleted = 0; while (deleteFirstMatch(list, searchVal)) { numDeleted++; }
return numDeleted; }
利用删除第一个匹配节点的函数,可以很轻松的实现删除所有匹配节点。这个函数的性能依然存在优化空间。
About this Post
This post is written by Jinyuan Zhou, licensed under CC BY-NC 4.0.