学习嵌入式第九天

23 篇文章 0 订阅

第九天

指针结构体回顾:a

1.c语言基础之链表

1.1 链表是一种数据结构

将零散的结构体通过指针的方式建立联系,就是链表。每个结构体称为节点。即上一个节点中存放着一个指针指向下一个节点的地址。最后节点中的指针指向NULL。

1.2 动态生成链表

  • 尾插法:使head指针和tail指针指向同一个节点,初始化new节点(新节点)使其指向NULL,然后让tail->next = new与新节点建立联系; 然后使tail指向new节点,使new节点成功加入链表。
  • 头插法:使head指针和tail指针指向同一个节点,该节点指向NULL,并且使新节点指向head,new->next=head,然后使tail指向新节点,head=new。这样新节点就从链表头部加入了新节点。
  • 注意:在遍历节点时,一定要使指针走向下一个节点,即加上 p=p->next;在这里插入图片描述
  • 实例代码中initLink如果不采用返回值返回链表的首地址的话可以使用传入链表首地址的地址(二级指针)来改变在main函数中的head的值。因为我们知道,要在A函数中直接改变B函数中的值,需要把B函数中的值的地址传给A函数,因为在本例中stu本来就是指针,所以传了二级指针。void initLink(struct Student **p){};

尾插法代码示例:

#include <stdio.h>
#include <stdlib.h>

struct Student {
    int num;
    struct Student *next;
};

struct Student *initLink() {
    int n;
    int i;
    printf("How Many Point you want?\n");
    scanf("%d", &n);
    struct Student *head = (struct Student *)malloc(sizeof(struct Student));
    printf("input no.1 num\n");
    scanf("%d",&head->num);
    head->next = NULL;
    struct Student *tail = head;
    for (i = 0; i < n-1; i++) {
        // init node
        struct Student *new = (struct Student *)malloc(sizeof(struct Student));
        printf("please input no.%d num\n", i + 2);
        scanf("%d", &new->num);
        new->next = NULL;
	
        // tail->next = new;
        tail->next = new;

        // tail = new;
        tail = new;
    }

    return head;
}

void printLink(struct Student *p) {
    while (p) {
        printf("%d\n", p->num);
        p = p->next;
    }
}

int main() {
    struct Student *head;
    head = initLink();
    printLink(head);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值