链表的遍历、创建、插入、删除

链表的遍历、创建、插入、删除


首先创建一个结构体类型:
struct Student{
int num;
char name[128];
struct Student *next;
};
在主函数main中定义顶一个head作为链表的头指针,用来做遍历、创建、插入、删除
int main()
{
struct Student *head;
head=initStudent(head);
lianbiao(head);

}
1. 链表的遍历:
链表的遍历操作是指将定义一个结构体指针p,将头指针head给p,使得指针p指向头指针head,然后利用p循环遍历整个链表,直到p==NULL,结束遍历。
void bianli(struct Student *head)
{
struct Student p=head;
while(p!=NULL)
{
printf(“num=%d name=%s”,p->num,p->name);
p=p->next;
}
}
2.链表的创建:
链表的创建操作是指定义三个结构体指针head,new,tail,分别用来作为链表的头指针,用于存储新的链表数据的新指针以及用于做创建插入跟踪胡尾指针。
struct Student
initStudent(struct Student *head)
{
struct Student *new;
struct Student *tail;

head=(struct Student *)malloc(sizeof(struct Student));
head->num=1;
strcpy(head->name,“chen”);
tail=head;
while(1)
{
new=(struct Student *)malloc(sizeof(struct Student));
new->num=2;
strcpy(new->name,“wang”);
tail->next=new;
tail=new;
}
}
3.链表的插入(从中间插入)
链表的插入操作其实很简单,在遍历过程中如果找到需要插入的位置,则使要插入的指针的下一个地址指向要插入的位置的指针所指向的地址,即可完成插入。
int charu(struct Student *head,int i,struct Student *k)
{
struct Student *p=head;
while(p!=NULL)
{
if(p->numi)
{
k->next=p->next;
p->next=k;
}
p=p->next;
}
}
4.链表的删除
int shanchu(struct Student *head,int i)
{
struct Student *p=head;
struct Student *temp=NULL;
while(p!=NULL)
{
if(p->next->num
i)
{
temp=p->next;
p->next=temp->next;
free(temp);
}
p=p->next;
}
return 0;
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值