c程序语言的链表创建,插入与删除
最近学习c语言的链表,总结了来链表的创建插入删除的基本技巧。希望能帮到初学者。
1.链表的创建
代码如下:
#include<stdio.h>
#include<stdlib.h>
#define len sizeof(struct stu)//定义len的长度为stu结构体的长度
struct stu //定义结构体,包含一个num的整数
{
int num;
struct stu *next;
};
struct stu *creat() //创建链表的函数
{
struct stu *p1,*p2,head;
p1=(struct stu)malloc(len); //开辟一个空间给p1
scanf("%d",&p1->num);
head=NULL;
while(p1->num!=0)
{
if(head==NULL)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct stu *)malloc(len);
scanf("%d",&p1->num);
}
p2->next=NULL;
return head;
}
int main()
{
struct stu *p;
p=creat(); //调用函数
while(p!=NULL)
{
printf("%d\t",p->num);
p=p->next;
}
return 0;
}
先创建一个空间给p1,输入p1的num,且head为null(空),把第一个p1给head,再把p1给p2,创建一个空间给p1,这时head不为空,就p2->next=p1,继续创建p1的空间,直到输入0,结束链表的输入。并且让p2->next=NULL;建立链表的过程就是这样;有不清楚的可以私信,下一篇就是链表的插入