Linked List 实例

时间:2022-10-23 19:04:22

文件功能:实现了动态建立一个学生信息的链表包括链表的
创建、插入、删除、和打印输出学生信息包括姓名和分数

#include<iostream>
#include<string>
using namespace std; //单个节点
struct Node
{
//Data
string name;
double score; //Pointer
Node* next;
}; typedef Node ListNode; //创建链表
ListNode* CreateList()
{
ListNode* head=new ListNode;//指向头结点指针
ListNode*p, *pre;
head->next = NULL;
pre = head;
cout << "Input name of the student:" << endl;
string name;
cin >> name;
cout << "Input his score:" << endl;
double score;
cin >> score; while (name!="q")
{
p = new ListNode;
p->name=name;
p->score=score;
pre->next = p;
pre = p;
cout << "Input name of the student(q to quit input)" << endl;
cin >> name;
if (name != "q")
{
cout << "Input his score:" << endl;
cin >> score;
}
}
pre->next = NULL;
return head;
} //输出链表
void PrintList(ListNode *h)
{
ListNode*p;
p = h->next;
while (p)
{
cout << p->name << " " << p->score << endl;
p = p->next;
}
} //在位置i插入链表
void InsertList(ListNode *L, int i, string name, double score)
{
ListNode *p, *q;
p = L;
int j = 0;
while (p&&j < i - 1)
{
p = p->next;
j++;
}
if (!p)return;
q = new ListNode;
q->name = name;
q->score = score;
q->next = p->next;
p->next = q;
} //删除节点
void Delete(ListNode*L, int i)
{
ListNode*p, *q;
p = L;
int j = 0;
while (p&&j < i - 1)
{
p = p->next;
j++;
}
if (!p)return;
q = p->next;
p->next = q->next;
delete q;
} //按位搜索节点
void Search(ListNode*L, int i)
{
ListNode*p=L;
int j = 0;
while (p&&j < i - 1)
{
p = p->next;
j++;
}
if (!p)return;
cout << "第" << i << "个学生" << ":";
cout << p->next->name << " " << p->next->score << endl;
} //按名字搜索节点
void Searchz(ListNode*L, string name)
{
ListNode*p;
p = L;
int j = 0;
while (p && (p->next->name) != name)
{
p = p->next;
j++;
}
if (!p)
{
cout << "Not Found" << endl;
return;
}
else
{
cout << p->next->name << " " << p->next->score << endl;
}
} //主函数
int main()
{
ListNode*head;
head = CreateList();
string name1, name2;
double score;
int j, j1, j2; cout << "1--输出链表" << endl;
cout << "2--添加元素" << endl;
cout << "3--删除元素" << endl;
cout << "4--按位输出元素" << endl;
cout << "5--按名字输出元素" << endl;
cout << "0--退出" << endl;
int i;
cin >> i;
while (i)
{
switch (i)
{
case 1:
PrintList(head);
break;
case 2:
cout << "请输入学生位置:";
cin >> j;
cout << "名字:";
cin >> name1;
cout << "成绩:";
cin >> score;
InsertList(head, i, name1, score);
PrintList(head);
break;
case 3:
cout << "输入要删除学生位置:";
cin >> j1;
Delete(head, j1);
PrintList(head);
break;
case 4:
cout << "请输入学生位置:";
cin >> j2;
Search(head, j2);
break;
case 5:
cout << "请输入学生姓名:";
cin >> name2;
Searchz(head, name2);
break;
default: cout << "ERROR! Try again!" << endl;
}
cin >> i;
}
delete head; return 0;
}