#include <stdio.h>
#include <stdlib.h>
typedef int item_type;
typedef struct _node{
item_type data;
struct _node *next;
}Node, List;
/*头插法,传入指向首元素地址的指针和要插入的元素*/
void insert_list(List **pList, item_type x){
Node *temp;
temp = (Node *)malloc(sizeof(Node));
temp->data = x; /*填充新结点*/
temp->next = *pList;
*pList = temp; /*更新首元素地址*/
}
/*递归搜索元素*/
List *search_list(List *l, item_type x){
if(l == NULL)
return NULL;
if(l->data == x)
return l;
else
return search_list(l->next, x);
}
/*递归找出元素的前驱*/
List *previous_list(List *l, item_type x){
if(l == NULL || l->next == NULL){
printf("Error: previous sought no null list.\n");
return NULL;
}
if((l->next)->data == x)
return l;
else
return previous_list(l->next, x);
}
/*删除元素,必须先找出前驱*/
void delete_data(List **pList, item_type x){
List *p; /*指向待删除项的指针*/
List *pred; /*前驱指针*/
p = search_list(*pList, x);
if(p != NULL){
pred = previous_list(*pList, x);
if(pred == NULL) //关键,如果删的是首元素!
*pList = p->next;
else
pred->next = p->next;
}
free(p);
}
/*打印列表*/
void print_list(List *l){
if(l == NULL){
puts("Print list error!");
return;
}
while(l != NULL){
printf("%d ", l->data);
l = l->next;
}
putchar('\n');
}
/*销毁链表*/
void delete_list(List **pHead){
Node *p, *tmp;
p = (*pHead); //p是首元素地址
pHead = NULL; //把头指针设置为NULL
while(p != NULL){
tmp = p->next;
free(p);
p = tmp;
}
}
int main(){
int i;
List *pList = NULL;
List **pHead = &pList;
for(i = 1; i < 10; ++i)
insert_list(&pList, i*4);
//List *pred = previous_list(pList, 36);
//if(pred == NULL)
// puts("yes");
//else
// puts("no");
print_list(pList);
delete_data(&pList, 4);
print_list(pList);
delete_list(pHead);
return 0;
}