C语言中怎么定义链表,最好把各个代码都详细的解释一下!

Python027

C语言中怎么定义链表,最好把各个代码都详细的解释一下!,第1张

/*creat

a

list*/

#include

"stdlib.h"

#include

"stdio.h"

struct

list

{

int

data

struct

list

*next

}

typedef

struct

list

node

typedef

node

*link

void

main()

{

link

ptr,head

int

num,i

ptr=(link)malloc(sizeof(node))

ptr=head

printf("please

input

5

numbers==>\n")

for(i=0i<=4i++)

{

scanf("%d",&num)

ptr->data=num

ptr->next=(link)malloc(sizeof(node))

if(i==4)

ptr->next=NULL

else

ptr=ptr->next

}

ptr=head

while(ptr!=NULL)

{

printf("The

value

is

==>%d\n",ptr->data)

ptr=ptr->next

}

}

上面是一个简单的创建链表的C程序。所谓链表形象的讲就是一个数据块里面存有数据,并且存有下一个数据的指针,这样一个指一个形成一个数据链。这个数据链可以被操作,例如插入数据,删除数据,等。至于指令,首先定义一个结构体,它存有数据和指向下一个数据块的指针。然后分配空间。注意最后一个为NULL,当然你也可以指向开头一个数据块形成一个循环链表。

这个是我曾经编写的一个管理里面的一个模块

就是按链表的某个变量进行排序的

希望您能看明白

Ranking_inquires(struct

student

*head)

{

int

B=A,i=0

struct

student

*temp=head

struct

student

*p=head

struct

student

*q=head

printf("\t\t

按总分

名次查询

\n

")

printf("姓名

总分

名次\n")

while(p->next!=NULL&&A>1)//根据成员的成绩对结构体

进行排序

{

p->sum=p->math+p->English+p->chinese+p->computer

q=p->next

p=p->next

while(q->next!=NULL)

{

q=q->next

if(p->sum

sum)

{

h.stu_id1=p->stu_id

strcpy(h.name1,p->name)

h.English1=p->English

h.computer1=p->computer

h.math1=p->math

h.sum1=p->sum

h.chinese1=p->chinese

p->stu_id=q->stu_id

strcpy(p->name,q->name)

p->English=q->English

p->computer=q->computer

p->math=q->math

p->sum=q->sum

p->chinese=q->chinese

q->stu_id=h.stu_id1

strcpy(q->name,h.name1)

q->English=h.English1

q->computer=h.computer1

q->math=h.math1

q->sum=h.sum1

q->chinese=h.chinese1

}

}

A--

++i

p->ranking=i

}

这个是定义的全局变量

int

A=0

int

cc

struct

student

{

int

stu_id

char

name[20]

float

English

float

computer

float

chinese

float

math

float

sum

int

ranking

struct

student

*next

}

struct

stu

{

int

stu_id1

char

name1[20]

float

English1

float

computer1

float

chinese1

float

math1

float

sum1

}h

主函数里调用就像写函数定义一样,比如调用创建表的,就这样:

#include <stdio.h>

struct Linklist { 

    ...

}

typedef Linklist* LinkList

   

int CreateList(LinkList LstMe) {

    ...

}  

  

int main() {

    LinkList LstDemo = (LinkList) malloc (sizeof(Linklist))

    CreateList(LstDemo) // 调用建表

    free (LstDemo)

    return 0

}