关于链表:相同类型的结点占有同样大小的内存空间,在使用过程中,为了解决结点数目动态变化问题,链表是一种有效的解决办法。例如使用动态存续的方法存续学生的成绩,对学生成绩的插入和删除。
创建一个链表,先创建它的头结点,结点分为指针域和数据域,第一个结点的指针域存入第二个结点的首地址,以此类推,最后一个指针域可赋为NULL。
结构体类型:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct student
{ int score;
struct student *next;
};
链表的建立:
建立一个头结点:
struct student*create()
{
struct student headNode=(struct student)malloc(sizeof(struct student));
headNode->next=NULL;
return headNode;
}
建立链表:
struct student *creatNode(int score)
{
struct student listNode=(struct student )malloc(sizeof(struct student));
listNode->next=NULL;
listNode->score=score;
return listNode;
}
插入结点:
void insertNode(struct student headNode,int score)
{
struct student newNode=creatNode(score);
newNode->next=headNode->next;
headNode->next=newNode;
}
删除结点:
void except(struct student *headNode,int posscore)
{
struct student *posNode=headNode->next;
struct student *posNodefront=headNode;
if(posNodeNULL)
{
printf(“无法删除”);
}
else
{while(posNode->score!=posscore)
{
posNodefront=posNode;
posNode=posNodefront->next;
if(posNodeNULL)
{
printf(“没有找到,无法删除”);
return ;
}
}
posNodefront->next=posNode->next;
free(posNode) ;
}
对链表输出函数:
void printList(struct student *headNode)
{
struct student *Pmove=headNode->next;
while(Pmove)
{
printf("%d",Pmove->score );
Pmove=Pmove->next;
}
printf("\n");
}
对上面的调用插入:
int main()
{
struct student * List=create();
insertNode(List,1);
insertNode(List,2);
insertNode(List,3);
printList(List);
except(List,2);
printList(List);
return 0;
}
链表还有结点的查找。