张彬彬 发小 助理:c语言链表的用途是什么

来源:百度文库 编辑:高考问答 时间:2024/04/29 12:07:22
为什么要用到链表?
最好详细一点

链表是一种常见的重要的数据结构。它是动态地进行存储分配的一种结构。它可以根据需要开辟内存单元。链表有一个“头指针”变量,以head表示,它存放一个地址。该地址指向一个元素。链表中每一个元素称为“结点”,每个结点都应包括两个部分:一为用户需要用的实际数据,二为下一个结点的地址。因此,head指向第一个元素:第一个元素又指向第二个元素;……,直到最后一个元素,该元素不再指向其它元素,它称为“表尾”,它的地址部分放一个“NULL”(表示“空地址”),链表到此结束。

1、链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。 相比于线性表顺序结构,链表比较方便插入和删除操作。
2、例程:

/*
*对链表的综合操作
*功能有建立,排序,插入,删除,输出
*/
#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct NodeType
{
ElemType data;
struct NodeType *next;
} NodeType,*LinkType;
LinkType create()
{//建立链表,返回链表的首地址,头结点没有数据
LinkType head,p1,p2;
head=(LinkType)malloc(sizeof(NodeType));
p1=head;
while(p1->data!=0)//当data=0时链表结束
{
p2=p1;
p1=(LinkType)malloc(sizeof(NodeType));
printf("Enter student's information:\ndata=");
scanf("%d",&p1->data);
p2->next=p1;
}
p2->next=NULL;
free(p1);
return(head);
}
void output(LinkType head)
{//链表的输出,接收链表的首地址
head=head->next;
while(head!=NULL)
{
printf("data=%d\n",head->data);
head=head->next;
}
}
LinkType sort(LinkType head)
{//链表排序,接收链表首地址,返回链表首地址
LinkType ph,p1;
ElemType temp;
ph=head->next;
p1=head->next;
while(p1->next!=NULL)//冒泡法
{
ph=head;
while(ph->next!=NULL)
{
if(ph->data>ph->next->data)//按data由小到大排序
{
temp=ph->data;
ph->data=ph->next->data;
ph->next->data=temp;
}
ph=ph->next;
}
p1=p1->next;
}
return(head);
}
LinkType del(LinkType head)
{//删除结点,接收链表的首地址,返回链表的首地址
ElemType DelData;
LinkType ph,p;
ph=head->next;
printf("Enter the data you want to del:\nDelData=");
scanf("%d",&DelData);
while(ph!=NULL && ph->data!=DelData)//寻找要删除的结点
{
p=ph;
ph=ph->next;
}
if(ph==NULL)//没有找到要删除的结点
{
printf("Enter error!\n");
return(head);
}
else
{
if(ph==head->next)//删除头结点
{
head->next=ph->next;
}
else//删除其它结点
{
p->next=ph->next;
}
}
free(ph);
return(head);
}
LinkType insert(LinkType head)
{//插入结点,接收链表首地址,返回链表首地址
LinkType ph,p,insert,temp;
insert=(LinkType)malloc(sizeof(NodeType));
printf("Enter the data you want to insert:\ndata=");
scanf("%d",&insert->data);
ph=head->next;
while(ph!=NULL && ph->data < insert->data)//寻找插入的位置
{
p=ph;
ph=ph->next;
}
if(head->next->data > insert->data)//插入头部
{
temp=head->next;
head->next=insert;
insert->next=temp;
}
else//插入到其它地方
{
p->next=insert;
insert->next=ph;
}
return(head);
}
void main()
{
LinkType head;
head=create();
output(head);
printf("\n\n");
head=sort(head);
output(head);
printf("\n\n");
head=del(head);
output(head);
printf("\n\n");
head=insert(head);
output(head);
}

用来存储逻辑地址连序而物理地址不一定连序的数据存储结构

是一种存储数据的结构方式

可以作为临时存储容器