简单静态、动态链表的建立

来源:互联网 发布:c语言unsigned long 编辑:程序博客网 时间:2024/04/29 11:33

静态链表的建立:

#include <stdio.h>struct student{int number;float score;struct student *next;};                                 //结点的定义int main(){struct student *head,*p,a,b,c;a.number=1234,a.score=90.5;b.number=1235,b.score=80.9;c.number=1238,c.score=97.6;head=&a,a.next=&b,b.next=&c,c.next=NULL,p=head;do                                         //输出此静态链表{printf("%ld,%6.2f\n",p->number,p->score);    p=p->next;}    while(head!=NULL);return 0;}
静态链表较为简单,只需注意指针域的链接,最后一个指针为空指针。在依次输出链表就行了


单向动态链表:

#include <stdio.h>#include <stdlib.h>#define LEN sizeof(struct student)    struct student    {        int num;        float score;        struct student *next;    };                                     //节点的定义    struct student* creat(void)     //编写创建动态链表的函数    {        struct student *p1,*p2,*head;        p1=p2=(struct student*)malloc(LEN);        scanf("%d %f",&p1->num,&p1->score);        head=p1;        while(p1->num)        {            p2->next=p1;     //A  line            p2=p1;           //B  line            p1=(struct student*)malloc(LEN);            scanf("%d %f",&p1->num,&p1->score);                 }        p2->next=NULL;        return (head);                        //返回值为创建的动态链表的头指针    }int main(){    struct student *pt,*p;    pt=creat();    p=pt;    if(p!=NULL)    do                                        //输出动态链表    {       printf("%d %5.1f\n",p->num,p->score);        p=p->next;    }while(p!=NULL);    return 0;}

A和B行的位置很关键,若放在scanf的后面,输出链表的时候就会把 0 0给输出来了,因此要放在前面。 建立动态链表的返回值是一个指针,指向结构体的指针。

构建好了后,再输出链表就行了,方法和静态链表的输出方法一样。