學生資料查詢系統
阿新 • • 發佈:2022-02-11
#include <iostream> #include <cstring> #include <iomanip>//設定域寬標頭檔案 using namespace std; typedef struct Link *List; typedef struct Link { string name; string sex; int age; int num; double score[3]; int total; int size; struct Link *next; } Link; List creat() { //建立連結串列 int n; List head, p; head = p = new Link; cout << "輸入班級總人數" << endl; cin >> n; cout << "請輸入" << n << "位學生的資料" << endl; head->size = n; while (n--) { p->next = new Link; p = p->next; p->total = 0; cin >> p->name >> p->num >> p->age >> p->sex; cout << "語文" << endl; cin >> p->score[0]; cout << "數學" << endl; cin >> p->score[1]; cout << "英語" << endl; cin >> p->score[2]; for (int i = 0; i < 3; i++) p->total += p->score[i]; } p->next = NULL; return head; } void output(List head) { //輸出 List x = head->next; if (x == NULL) { cout << "此表為空表" << endl; return ; } cout << "班級學生資料如下" << endl; cout << setw(10) << "學號" << setw(10) << "姓名" << setw(10) << "性別" << setw(10) << "年齡" << setw( 10) << "語文" << setw(10) << "數學" << setw(10) << "英語" << setw(10) << "總分" << endl; while (x != NULL) { cout << setw(10) << x->num << setw(10) << x->name << setw(10) << x->sex << setw(10) << x->age << setw( 10) << x->score[0] << setw(10) << x->score[1] << setw(10) << x->score[2] << setw(10) << x->total << endl; x = x->next; } } void deleteList(List head) { //刪除整個連結串列 List x = head; while (x) { head = x->next; delete x; x = head; } } List find(List head, int i) { //查詢 List x = head; int j = 0; if (i < 0 || i > x->size) { cout << "輸入錯誤位置資訊" << endl; return NULL; } while (j < i && x) { x = x->next; j++; } return x; } void insert(List head, Link p, int i) { //插入 List x, y; x = find(head, i - 1); if (x == NULL) return ; else { y = new Link; *y = p; y->next = x->next; x->next = y; head->size++; } } void delete_student(List head, int i) { //刪除某個同學資料 List p, q; if (i < 0 || i > head->size) { cout << "刪除位置錯誤" << endl; return ; } p = find(head, i - 1); q = p->next; p->next = q->next; head->size--; delete q; } int main() { List head, p; Link x; head = creat(); //建立 output(head);//輸出 int n; cout << "輸入你要查詢的學生位置" << endl; //查詢 cin >> n; p = find(head, n); if (p) { cout << "找到第" << n << "名學生資訊是" << endl; cout << setw(10) << p->num << setw(10) << p->name << setw(10) << p->sex << setw(10) << p->age << setw( 10) << p->score[0] << setw(10) << p->score[1] << setw(10) << p->score[2] << setw(10) << p->total << endl; } cout << "請輸入你要新增的學生位置" << endl; //插入 cin >> n; cout << "請輸入你要新增的學生資訊" << endl; cin >> x.name >> x.num >> x.age >> x.sex; cout << "語文" << endl; cin >> x.score[0]; cout << "數學" << endl; cin >> x.score[1]; cout << "英語" << endl; cin >> x.score[2]; for (int i = 0; i < 3; i++) x.total += x.score[i]; insert(head, x, n); cout << "插入後的資訊為:" << endl; output(head); cout << "請輸入要刪除學生資訊的節點位置:" << endl; cin >> n; delete_student(head, n); output(head); return 0; }