建立一個(gè)鏈表,每個(gè)結(jié)點(diǎn)包括:學(xué)號(hào)疤苹、性別互广、年齡,輸入一個(gè)學(xué)號(hào)痰催,如果鏈表中的結(jié)點(diǎn)包括該學(xué)號(hào),則輸出該結(jié)點(diǎn)內(nèi)容后迎瞧,并將其結(jié)點(diǎn)刪去夸溶。
#include <iostream>
using namespace std;
typedef struct Node{
int id;
char gender[10];
int age;
struct Node *next;
} node;
// 初始化頭結(jié)點(diǎn)
void LinkListInit(node *p){
p = new node();
p->next = NULL;
}
// 插入節(jié)點(diǎn)
void LinkListInput(node *head, node *p){
p->next = head->next;
head->next = p;
}
// 添加節(jié)點(diǎn)
void LinkListAdd(node *head){
char ch;
while(1){
node *p = new node;
cout << "輸入\n學(xué)號(hào)\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;
}
}
// 刪除節(jié)點(diǎn)
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;
}
}
}
// 顯示所有的節(jié)點(diǎn)信息
void LinkListDisplay(node *head){
node *p = head->next;
cout << "\n學(xué)號(hào)\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 << "要?jiǎng)h除的學(xué)號(hào):" <<endl;
cin >> id;
LinkListDelete(head, id);
LinkListDisplay(head);
return 0;
}