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;
}
运行结果
参考