动态链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangshuxuncom/article/details/85100244

动态链表:指在程序执行过程中从无到有地建立起一个链表,即通过malloc函数一个一个地开辟节点,然后输入新节点各成员数据,最后和前节点(如果当前节点不是首节点)建立起前后相链的关系的链表。

#include <stdio.h>

struct Node {
    int id;
    char name [100];
    struct Node * next;
};

struct Node * create() {
    int n = 1;
    struct Node * head;//存放链表第一个节点地址
    struct Node * tail;//存放链表最后一个节点地址
    struct Node * current;//存放新节点地址

    current = malloc(sizeof(struct Node));
    printf("请输入第%d个数据\n", n);
    scanf("%d,%s", &(*current).id, current->name);

    while(current->id != 0) {
        if(n == 1) {
            head = current;//n为1,意味着当前节点即是首节点;
        } else {
            tail->next = current;//把当前节点地址“挂到”之后一个节点的next成员;
        }
        tail = current;//将已加入链表的当前节点“变”为链表最后一个节点;

        n++;
        current = malloc(sizeof(struct Node));//动态生成新的、待加入链表的节点,如果新的节点id成员为0,则意味着停止向链表中添加节点
        printf("请输入第%d个数据\n", n);
        scanf("%d,%s", &current->id, (*current).name);
    }
    (*tail).next = NULL;
    return head;
}

void print(struct Node * head) {
    struct Node * point = head;
    int n = 1;
    if(point != NULL) {
        while(point != NULL) {
            printf("第%d个数据信息:%d,%s\n", n, point->id, point->name);
            point = point->next;//当遍历“完”链表最后一个元素时,point指针变量的值为NULL
            n++;
        }
    }
}

int main() {
    struct Node * head = create();
    print(head);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wangshuxuncom/article/details/85100244
今日推荐