链表

mac2024-04-06  33

#include "pch.h" #include <iostream> using namespace std; //双向列表,结构体表示 typedef struct node Student; //起别名 typedef struct node { char name[64]; int age; Student *next; Student *pre; }Student; //创建表 Student * createList( int n) { Student *head = new Student; //new创建空间 Student *q = head; *head->name ='No'; head->age = 0; for (int i = 0; i < n; i++) { Student *p = new Student; cout << "请输入第" << i + 1 << "个学生的姓名和年龄:"; cin >> p->name >> p -> age; q->next = p; p->pre = q; q = q->next; //q = p 也ok p->next = head; //双向循环链表 (包括了头节点) head->pre = p; } return head; } //显示表 void display(Student *head) { Student *p = head->next; int n; cout << "该双向链表的第一个元素为:"; cout << p->name << " " << p->age << endl; do { cout << "请输入数字,1为往下查询,2为往上查询,0结束查询"; cin >> n; if (n == 1) { p = p -> next; cout << "下一位学生为:" << p->name << " 年龄为:" << p->age << endl; } if (n == 2) { p = p->pre; cout << "上一位学生为:" << p->name << " 年龄为:" << p->age << endl; } } while (n != 0); } int main() { Student *head = createList(10); display(head); return 0; }
最新回复(0)