c语言链表用处,c语言链表的用途是什么

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

2、例程:

/*

*对链表的综合操作

*功能有建立,排序,插入,删除,输出

*/

#include

#include

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 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);

}