一、链表简介
1、链表的每个结点包含两个部分:
- 一个是数据域,用来存放待处理的数据
- 一个是指针域,用来存储下一个结点的地址
2、链表是一系列的结点通过指针进行连接起来的,其在内存地址中的位置并不连续,结点可以动态创建。链表不支持随机访问结点,只能从头结点逐个开始访问、遍历。
3、链表的每个结点是同一种结构体类型,结点的定义如下:
【注】指针域中的指针是指向下一个结点的,所以指针的类型就是定义该结点的结构体类型
struct ListNode
{
string name;
int score;
ListNode* next; // 存放下一个结点地址的指针域
};
二、链表常见操作
1、创建链表
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
// 定义结点
struct ListNode
{
string name;
int score;
ListNode* next; // 存放下一个结点地址的指针域
};
// 遍历链表,方式1
void PrintList01(ListNode* head)
{
ListNode* p = head;
while (p!= NULL)
{
cout << "name= " << p->name << " , score= " << p->score << endl;
p = p->next;
}
}
// 遍历链表,方式2
void PrintList02(ListNode* head)
{
// 若将判断条件修改为: p->next!=0 ,则尾结点不参与循环,不会输出最后一个结点的值,
for (ListNode* p = head; p!=NULL; p = p->next)
{
cout << "name= " << p->name << " , score= " << p->score << endl;
}
}
// 将结点连接起来创建链表
ListNode* CreateList()
{
// ListNode head; // 不用该类型,因为该类型在栈上,该函数调用完,就会被释放。
ListNode* head = new ListNode; // 在堆上创建,当该函数调用完仍然存在。
ListNode* p1 = new ListNode;
ListNode* p2 = new ListNode;
ListNode* p3 = new ListNode;
ListNode* p4 = new ListNode;
head->name = "F", head->score = 100;
p1->name = "A", p1->score = 80;
p2->name = "B", p2->score = 90;
p3->name = "C", p3->score = 78;
p4->name = "D", p4->score = 99;
// 通过指针将各个结点连接起来
head->next = p1;
p1->next = p2;
p2->next = p3;
p3->next = p4;
p4->next = NULL;
return head;
}
// 删除第 k 个结点
void DeleteList(ListNode* head,int k)
{
int num = 1;
for (ListNode *p = head , *temp = nullptr; p != NULL; p = p -> next)
{
if (num == k)
{
temp = p->next;
p->next = p->next->next;
delete temp;
break;
}
num++;
}
cout << "删除第" << k << "个结点后的链表" << endl;
PrintList01(head);
}
// 在第k个结点后插入新结点
void InsertNode(ListNode *head,int k)
{
ListNode *temp = new ListNode();
int num = 1;
temp->name = "The new node01", temp->score = 160;
for (ListNode *p1 = head; p1 != NULL; p1 = p1->next)
{
if (num == k)
{
temp->next = p1->next;
p1->next = temp;
}
num++;
}
cout << "在第" << k << "个结点处,插入新结点" << endl;
PrintList01(head);
}
int main()
{
ListNode* phead = CreateList();
cout << "第一种遍历列表方式" << endl;
PrintList01(phead);
cout << "--------------------" << endl;
cout << "第二种遍历列表方式" << endl;
PrintList02(phead);
cout << "--------------------" << endl;
DeleteList(phead, 2);
cout << "--------------------" << endl;
InsertNode(phead, 3);
system("pause");
}
结果如下图所示