第一次写C++链表,嘿嘿嘿,加油哈,大家。
#include<iostream>
using namespace std;
//用结构体类型来表示节点
typedef struct node
{
char name[20];
int age;
struct node* next;
}Student;
//创建链表
Student *creatList(int n)
{
Student* head = new Student;//头节点 一般不用于存储数据
Student* pre = head;
for (int i = 0; i < n; i++)
{
Student* p = new Student;
printf("请输入第%d学生的姓名与年龄", i + 1);
cin >> p->name;
cin >> p->age;
pre->next = p;
pre = p;
p->next = NULL;
}
return head;
}
void display(Student *head)
{
Student* p = head->next;
while (p)
{
cout << p->name << "," << p->age << endl;
p = p->next;
}
}
int main()
{
int n = 5;
Student *head=creatList(n);
display(head);
return 0;
}