动态链表和静态链表的区别

静态链表是用数组实现的,是顺序的存储结构,在物理地址上是连续的,而且需要预先分配大小。动态链表是用申请内存函数(C是malloc,C++是new)动态申请内存的,所以在链表的长度上没有限制。动态链表因为是动态申请内存的,所以每个节点的物理地址不连续,要通过指针来顺序访问。

*所有结点都是在程序中定义的,不是临时开辟的,也不能用完后释放,这种链表称为“静态链表”。*/
struct Student
{
    int num;
    float score;
    struct Student *next;
};
int main()
{
    struct Student stu1, stu2, stu3, *head, *p;
    stu1.num = 1001; stu1.score = 80; //对结点stu1的num和score成员赋值
    stu2.num = 1002; stu2.score = 85; //对结点stu2的num和score成员赋值
    stu3.num = 1003; stu3.score = 90; //对结点stu3的num和score成员赋值

    head = &stu1;      //头指针指向第1个结点stu1
    stu1.next = &stu2; //将结点stu2的地址赋值给stu1结点的next成员
    stu2.next = &stu3; //将结点stu3的地址赋值给stu2结点的next成员
    stu3.next = NULL;  //stu3是最后一个结点,其next成员不存放任何结点的地址,置为NULL
    p = head;          //使p指针也指向第1个结点

    //遍历静态链表
    do{
        printf("%d,%f\n", p->num, p->score); //输出p所指向结点的数据
        p = p->next;                         //然后让p指向下一个结点
    } while (p != NULL);                     //直到p的next成员为NULL,即完成遍历

    system("p
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
*所谓动态链表,是指在程序执行过程中从无到有地建立起一个链表,即一个一个地开辟结点和输入各结点数据,并建立起前后相链的关系。*/
struct Student
{
    int No;//学号
    struct Student *next;
};
int main()
{
    struct Student *p1, *p2, *head;
    int n = 0; //结点个数
    head = NULL;
    p1 = (struct Student *)malloc(sizeof(struct Student));
    printf("请输入1个学号\n");
    scanf("%d", &p1->No);
    p2 = p1; //开始时,p1和p2均指向第1个结点
    while (p1->No != 0)
    {
        n++;
        if (n == 1)
        {
            head = p1;
        }
        else
        {
            p2->next = p1;
        }
        p2 = p1;//p2是最后一个结点
        printf("请输入学号,输入0终止:\n");
        p1 = (struct Student *)malloc(sizeof(struct Student));
        scanf("%d", &p1->No);
    };
    p2->next = NULL;//输入完毕后,p2->next为NULL

    //遍历动态链表
    struct Student *p;
    p = head;
    while (p != NULL)
    {
        printf("%d,", p->No);
        p = p -> next;
    }
    printf("\n");

    system("pause");
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值