C++ 创建单向链表

#include <iostream>
using namespace std;

typedef struct node
{
    char name[20];
    int age;
    struct node *next;
}Student;

//创建链表
Student* createList(int n)
{
    //使头节点存在于栈上,函数执行完毕不会消失。头节点不储存内容
    Student *head = new Student;
    Student *pre = head;
    for (int i = 0; i < n; i++)
    {
        Student *p = new Student;
        cout << "第" << i + 1 << "个:输入姓名和年龄:";
        cin >> p->name;
        cin >> p->age;
        //借助pre实现链表衔接,这里pre指向p,pre->next也指向p
        pre->next = p;
        pre = p;
        p ->next = NULL; 
    }
    pre = NULL;
    return head;
}

void display(Student *head)
{
    Student *p = head -> next;
    for(;p != NULL;)
    {
        cout << "名称" << p->name << "年龄" << p->age << endl;
        p = p -> next;
    }
}

int main()
{
    int n = 3;
    Student *Student = createList(n);
    display(Student);
    return 0;
}

运行结果

image

参考

https://www.bilibili.com/video/BV1kx411g7Tj?from=search&seid=15546359323432902110&spm_id_from=333.337.0.0

posted @ 2022-03-09 09:54  混淆黑白  阅读(124)  评论(0编辑  收藏  举报