单向链表笔记
链表是由一系列连接在一起的结点构成,其中的每个结点都是一个数据结构。
特点:非连续、非顺序、线性、动态分配。
struct List
{
char name[20];
//结点名字 * 后继指针
List* next;//结点的后继指针
};
List* head;
int main() {
cout << "链表头的地址:" << &head << endl;
head = new List;
List* second = new List;
head->next = second;
second->next = NULL;
cout << "链表头指向第一个结点数据的地址:" << &head->name << endl;
cout << "链表头指向第一个结点后继指针的地址:" << &head->next << endl;
cout << "第二个结点数据的地址:" << &second->name << endl;
cout << "第二个结点后继指针的地址:" << &second->next << endl;
}
链表头的地址:014002D8
链表头指向第一个结点数据的地址:03470568
链表头指向第一个结点后继指针的地址:03470584
第二个结点数据的地址:03474868
第二个结点后继指针的地址:03474884
创建节点
Student* creat() {
Student* Node = new Student;//分配新节点的空间
cout << "输入名字:";
cin >> Node->name;
cout << "输入年龄:";
cin >> Node->age;
cout << "输入成绩:";
cin >> Node->score;
Node->next = NULL;//默认此节点的后继指针指向空,即是尾端
return Node;//返回新节点的指针
}
创建链表
Student* head;//链表的首指针
Student* pre;//保存链表当前末端指针
int num = 0;//记录当前链表结点个数
void add() {
//链表为空时
if (num == NULL) {
head = creat();
pre = head;//head成为当前链表末端
num++;
}
else {
Student* New = creat();
pre->next = New;//原链表末端后继指针->新节点
pre = New;//新节点成为链表末端
num++;
}
}
删除链表结点
void del() {
string n;
cout << "请输入删除的名字:";
cin >> n;
bool isexist = false;//标记是否存在
for (Student* cur = head; cur != NULL; cur = cur->next) {
Student* Next = cur->next;
//删除第一个
if (cur->name == n) {
head = Next;//下一个结点称为首指针指向的结点
delete cur;//释放当前结点的空间
num--;
isexist = true;
break;
}
//删除末尾的结点(下一个结点要删除并且在末端)
else if (Next->name == n && Next->next == NULL) {
cur->next = NULL;//当前的后继指针指向空,成为链表末端
pre = cur;//保存当前链表末端,避免继续添加会出错
delete Next;
num--;
isexist = true;
break;
}
//删除中间结点
else if (Next->name == n && Next->next != NULL) {
cur->next = Next->next;//当前结点的后继指针 = 下一个结点的后继指针
delete Next;
num--;
isexist = true;
break;
}
}
if (isexist == false) { cout << "不存在此信息,删除失败"; }
}