//声明结点类型
struct node{
int value;
struct node *next;
};
struct node *first=NULL; //记录链表开始位置:头指针
first=NULL;
//创建结点
struct node *new_node;
new_node=malloc(sizeof(struct node));
scanf("%d",&new_node->value);
new_node->next=first; //头插法
first=new_node;
//插入结点
struct node *add_to_list(struct node *list,int n){
struct node *new_node;
new_node=malloc(sizeof(struct node));
if(new_node == NULL){
printf("Malloc fail.");exit(EXIT_FAILURE);
}
new_node->value=n;
new_node->next=list;
return new_node;
}
first=add_to_list(first,10);
//创建链表
struct node *read_numbers(void){
struct node *first=NULL;
int value;
printf("Enter integers(0-exit):");
for(;;){
scanf("%d",&value);
if(value == 0)
return first;
first=add_to_list(first,value);
}
}
//搜索链表*****
strust node *seach_list(struct node *list,int value){
struct node *p;
for(p=list ; p != NULL; p=p->next){
if(p->value==value)
return p;
}
return NULL;
}
删除结点
定位要删除的结点;
改变前一个结点,使她“绕过”删除结点;
调用free函数收回删除结点的内存空间;
//删除结点
struct node *delete_from_list(struct node *list,int value){
struct node *cur,*prev;
for(cur=list,prev=NULL;cur != NULL && cur->value != value;prev=cur,cur=cur->next)
;
if(cur == NULL) return list;
if(prev == NULL) list=list->next;
else
prev->next=cur->next;
free(cur);
return list;
}