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

静态链表的建立:

#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给输出来了,因此要放在前面。 建立动态链表的返回值是一个指针,指向结构体的指针。

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



                
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值