前几天在网上查找资料是看到了有大牛用二级指针操作链表,然后呢,我也在此写出来与大家分享一下,同时呢也做一下笔记。
一般的,我们都是用一级指针做删除链表的工作,如下:
typedef struct node
{
struct node * next;
....
} node;
typedef bool (* remove_fn)(node const * v);
// Remove all nodes from the supplied list for which the
// supplied remove function returns true.
// Returns the new head of the list.
node * remove_if(node * head, remove_fn rm)//<span style="color: rgb(85, 85, 85); font-family: 'Open Sans', 'Helvetica Neue', 'Hiragino Sans GB', sans-serif, Arial, Verdana, 'BitStream vera Sans', Tahoma, Helvetica, sans-serif; font-size: 16px; line-height: 27.2px;">remove_fn由调用查提供的一个是否删除当前实体结点的函数指针,其会判断删除条件是否成//立。这段代码维护了两个节点指针prev和curr</span>
{
for (node * prev = NULL, * curr = head; curr != NULL; )
{
node * const next = curr->next;
if (rm(curr))
{
if (prev)
prev->next = next;
else
head = next;
free(curr);
}
else
prev = curr;
curr = next;
}
return head;
}
void remove_if(node ** head, remove_fn rm)
{
for (node** curr = head; *curr; )
{
node * entry = *curr;
if (rm(entry))
{
*curr = entry->next;
free(entry);
}
else
curr = &entry->next;
}
}
其过程如下:
代码例子:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int x;
struct node * next;
}node_t;
typedef int (* check_fn)(node_t* const v);
node_t* add_x(node_t* head,int x)
{
node_t* t = (node_t*)malloc(sizeof(node_t));
//what if malloc returns null ?
t->x = x;
t->next = NULL;
if(head){
t->next = head;
head = t;
}else{
head = t;
}
return head;
}
void show_list(node_t* head)
{
while(head){
printf("%d \t",head->x);
head = head->next;
}
printf("\n");
}
int check(node_t* const v)
{
if (v->x == 5)
return 1;
return 0;
}
node_t* remove_by_check(node_t* head,check_fn check)
{
node_t *prev, *cur;
prev = NULL;
for (cur = head;cur;){
if(check(cur)){
if(prev){
prev->next = cur->next;
}else{
head = cur->next;
}
free(cur);
}else{
prev = cur;
}
cur = cur->next;
}
return head;
}
/*void remove_by_check_better(node_t** head,check_fn check)
{
while (*head)
{
if(check(*head))
{
node_t* tmp = *head;
*head = (*head)->next;
free(tmp);
}
else
head = &((*head)->next);
}
}*/
void remove_by_check_better(node_t** head,check_fn check)
{
node_t** curr = head;
while(*curr)
{
node_t * entry = *curr;
if (check(entry))
{
*curr = entry->next;
free(entry);
}
else
curr = &entry->next;//这个语句执行之后,操作*curr和操作entry->next是一样的,都是操作同一个东西;
}
}
int main(void)
{
node_t *list = NULL;
list = add_x(list,1);
list = add_x(list,2);
list = add_x(list,3);
list = add_x(list,4);
list = add_x(list,5);
list = add_x(list,6);
show_list(list);
//list = remove_by_check_better(list,check);
remove_by_check_better(&list,check);
show_list(list);
return 0;
}