建立一个链表,每个结点包括:学号、性别、年龄,输入一个学号,如果链表中的结点包括该学号,则输出该结点内容后,并将其结点删去。
#include <iostream>
using namespace std;
typedef struct Node{
int id;
char gender[10];
int age;
struct Node *next;
} node;
// 初始化头结点
void LinkListInit(node *p){
p = new node();
p->next = NULL;
}
// 插入节点
void LinkListInput(node *head, node *p){
p->next = head->next;
head->next = p;
}
// 添加节点
void LinkListAdd(node *head){
char ch;
while(1){
node *p = new node;
cout << "输入\n学号\t" << "性别\t" << "年龄" << endl;
cin >> p->id >> p->gender >> p->age ;
cout << "save(y or n):" << endl;
cin >> ch;
if(ch == 'y'){
LinkListInput(head, p);
}else {
delete p;
}
cout << "Continue(y or n)" << endl;
cin >> ch;
if(ch == 'n') break;
}
}
// 删除节点
void LinkListDelete(node *head, int id){
node *p = head;
node *q = p;
while(p->next){
q = p;
p = p->next;
if(p->id == id){
q->next = p->next;
cout << p->id << '\t' << p->gender << '\t' << p->age << endl;
delete p;
p = q;
}
}
}
// 显示所有的节点信息
void LinkListDisplay(node *head){
node *p = head->next;
cout << "\n学号\t" << "性别\t" << "年龄" <<endl;
while(p){
cout << p->id << '\t' << p->gender << '\t' << p->age <<endl;
p = p->next;
}
}
int main(void){
node *head = new node;
LinkListInit(head);
LinkListAdd(head);
LinkListDisplay(head);
int id;
cout << "要删除的学号:" <<endl;
cin >> id;
LinkListDelete(head, id);
LinkListDisplay(head);
return 0;
}