程序:
#include<stdio.h>
#include<stdlib.h>
struct listdata{
int num;
struct listdata *next;
};
void deleteNode(struct listdata *node)
{
struct listdata *tmp;
tmp=node->next;
node->num=tmp->num;
node->next=tmp->next;
free(tmp);
}
struct listdata *find(int n,struct listdata const *node)
{
struct listdata *tmp;
tmp=node;
while(tmp)
{
if(tmp->num==n)
{
return tmp;
}
tmp=tmp->next;
}
return NULL;
}
void dayinlist(struct listdata *node)
{
struct listdata *tmp;
tmp=node;
printf("链表:\n");
while(tmp)
{
printf("%d\t",tmp->num);
tmp=tmp->next;
}
printf("\n");
}
int main()
{
printf("输入链表数据(-1结束):\n");
struct listdata *head=NULL;
struct listdata *new,*old;
while(1)
{
new = (struct listdata *) malloc(sizeof(struct listdata));
scanf("%d",&new->num);
if(new->num==-1)
{
break;
}
else
{
if(head==NULL)
{
head=new;
}
else
{
old->next=new;
}
}
new->next=NULL;
old=new;
}
dayinlist(head);
printf("输入要删除的数据:");
int n;
scanf("%d",&n);
struct listdata *tmp;
tmp=find(n,head);
if(tmp==NULL)
{
printf("未找到");
}
else
{
deleteNode(tmp);
dayinlist(head);
}
return 0;
}
比较顺利,没遇到什么大问题,链表前段时间熟悉过。
知识点
1.定义一个返回结构体指针的函数:
定义一个结构体:
struct 结构体名{};
定义结构体函数:
struct 结构体名 *(…)
{
//定义结构体数据
struct 结构体名 变量名{};
…
return 变量名;
}
2.向函数传结构体指针:
void 函数名(struct 结构体名 *(形参名))
3.定义一个结构体指针后,获取其中参数用->,例如node->num 。这种情况下用scanf赋值时,依然要加“&”
4.创建链表时必须有三个指针,head,new,old,之前一直纠结于是不是可以省取head这个头指针,这次发现,头指针是最重要的,头指针就是链表的代表,头指针就可以说是链表名,后面的new和old指针只是在构建链表的过程中用来过度的,链表创建完成就没什么用了