链表比数组的优点是,方便增删;因为数组中的元素都是连续的,增删起来非常不便。
#include <stdio.h>
struct Students
{
int score;
struct Students *p;
};
int main()
{
struct Students stu1 = {29,NULL};
struct Students stu2 = {69,NULL};
struct Students stu3 = {36,NULL};
stu1.p = &stu2;
stu2.p = &stu3;
printf("stu1 = %d,stu2 = %d,stu3 = %d\n",stu1.score,stu1.p->score,stu1.p->p->score);
return 0;
}
链表的增、查询,节点后、后插入新元素
#include <stdio.h>
struct Students
{
int score;
struct Students *next;
};
void ptintlink(struct Students *p)
{
struct Students *point;
point = p;
while(point != NULL)
{
printf("%d ",point->score);
point = point->next;
}
putchar('\n');
}
int searchlink(struct Students *point,int data)
{
struct Students *head;
head = point;
while(head != NULL)
{
if(head->score == data)
{
return 1;
}
head = head->next;
}
return 0;
}
struct Students *inserFromfor(struct Students *head,int data,struct Students *new)//节点前插入
{
struct Students *point;
point = head;
if(point->score == data)
{
new->next = head;
return new;
}
while(point != NULL)
{
if(point->next->score == data)
{
new->next = point->next;
point->next = new;
return head;
}
point = point->next;
}
return head;
}
int inserFromBehind(struct Students *head,int data,struct Students *new)//节点后插入
{
struct Students *point;
point = head;
while(point != NULL)
{
if(point->score == data)
{
new->next = point->next;
point->next = new;
return 1;
}
point = point->next;
}
return 0;
}
int main()
{
struct Students *head;
struct Students stu1 = {10,NULL};
struct Students stu2 = {20,NULL};
struct Students stu3 = {30,NULL};
struct Students stu4 = {40,NULL};
struct Students stu5 = {50,NULL};
struct Students stu31 = {39,NULL};
stu1.next = &stu2;
stu2.next = &stu3;
stu3.next = &stu4;
stu4.next = &stu5;
/*结点前插入
head = &stu1;
ptintlink(&stu1);
putchar('\n');
head = inserFromfor(&stu1,50,&stu31);
ptintlink(head);*/
/*节点后插入
int ret;
ret = inserFromBehind(&stu1,50,&stu31);
if(ret == 1)
{
putchar('\n');
ptintlink(&stu1);
printf("已插入\n");
}
else
{
printf("没找到\n");
}*/
/*查询
int ret;
ret = searchlink(&stu1,1);
if(ret == 1)
{
printf("找到了\n");
}
else
{
printf("没找到\n");
}*/
return 0;
}