链表与数组不一样,链表可以动态创建储存空间,可以存放不连续的数据,数组存放的是连续的一串数据。
链表由一系列的节点组成,链表的节点实际上就是结构体变量,节点中通常有一个数据和一个指针。
链表的初始化:例:学生
struct Student()
{
int score;
struct Student *next;
};
int main()
{
链表的初始化:
struct Student *stu1;
struct Student *stu2;
struct Student *stu2;
stu1=(struct Student *)malloc((sizeof)struct Student );
stu2=(struct Student *)malloc((sizeof)struct Student );
stu3=(struct Student *)malloc((sizeof)struct Student );
stu1->score=1;
stu1->next=stu2;
stu2->score=2;
stu2->next=stu3;
stu3->score=3;
stu3->next=NULL;
}
struct Student *head=NULL;
struct Student *tail=NULL;
struct Student *new=NULL;
head=(struct Student *)malloc((sizeof)struct Student );
head->score=100;
int i;
头插法:
for(i=0;i<3;i++){
while(head->next!=NULL)
{
new=(struct Student *)malloc((sizeof)struct Student );
new->i;
new->next=head;
head=new;
}
}
尾插法:
head=tail;
for(i=0;i<3;i++)
{
new=(struct Student *)malloc((sizeof)struct Student );
tail->next=new;
tail=new;
}
tail->next=NULL;
链表的遍历:
struct Student *head;
head=stu1;
while(head->next!=NULL)
{
printf("%d\n",head->score);
head=head->next;
}
链表的插入:假设在stu1之后插入一个结点stu4;
struct Student *stu4;
stu4=(struct Student *)malloc((sizeof)struct Student );
stu4->score=4;
stu4->next=stu1->next;
stu->next=stu4;
链表的查找:
先遍历链表。如果找到某个需要的score,那么就把整个stu输出;
链表的删除:假设把stu2删除;
struct Student *p=NULL;
p=stu2;
stu1->next=->p-next;
free(p);