显示所有节点数据:
void all(Student *p)
{
cout << "显示全部节点数据" << endl;
while (p != NULL)
{
cout << p->num << setw(10) << p->name << endl;
p = p->next;
}
}
取值:
void getelem(Student *p, int i)//取值
{
cout << "取值" << endl;
int j = 1;
while (p != NULL && j < i)
{
p = p->next;
j++;
}
if (p != NULL) cout << p->num << setw(10) << p->name << endl;
else cerr << "该位置无元素" << endl;
}
查找:
bool find(Student *p, string num, string name)
{
cout << "查找" << endl;
while (p!=NULL&&num!=p->num&&name!=p->name)
{
p->next;
}
if (p != NULL)
{
cout << p->num << setw(10) << p->name << endl;
cout << "成功找到" << endl;
return true;
}
else cout << "查无此人" << endl;
}
插入数据:
void insert(Student *p, Student *in,int i)
{
cout << "插入" << endl;
int j = 1;
while (j < i&&p != NULL)
{
j++;
p = p->next;
}
if (j < i) cout << "找不到该节点" << endl;
else
{
in->next = p->next;
p->next = in;
cout << "插入完成" << endl;
}
}
删除数据:
void deletes(Student *p, int i)
{
int j = 1;
while (p != NULL && j < i)
{
j++;
p = p->next;
}
if (j < i) cout << "该节点为空,无法删除" << endl;
else
{
Student *q = p->next;
p->next = q->next;
//delete q;
cout << "删除成功" << endl;
}
}
#include "pch.h"
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<string>
#include<cstring>
using namespace std;
struct Student
{
string num;//学号
string name;//姓名
struct Student *next;
};
void all(Student *p);//显示所有数据
void getelem(Student *p, int i);//取值
bool find(Student *p, string num, string name);//查找数据
void insert(Student *p, Student *in,int i);//插入数据
void deletes(Student *p,int i);//删除数据
int main()
{
struct Student a, b, c, *head, *p;
a.num = "1";
a.name = "first";
a.next = &b;
b.num = "2";
b.name = "second";
b.next = &c;
c.num = "3";
c.name = "third";
c.next = NULL;//对结构中各数据赋值并链接节点
head = &a;
p = head;
all(p);
cout << endl;
getelem(p, 2);
cout << endl;
find(p, "1", "first");
cout << endl;
struct Student in;
in.num = "4";
in.name = "fourth";
insert(p, &in, 2);
all(p);
cout << endl;
deletes(p, 2);
all(p);
}