简单讲解一下:
链表又称链式存储不像数组空间是连续的,数组是每插入或删除都要移动原有数据的位置补齐连接,以至于数组可以达到遍历输出。链表是线性存储,每次插入依靠指针与数据域。指针指向数据域达到连接的效果(具体就不讲解了)
链表分很多种,比如循环链表,双向链表。想要搞出链表其实不难,但只要是关于链式存储的都要依赖指针,所以有时其中的逻辑会很绕脑!
这里讲解一下单链表的操作:
- 定义指针域类(其中包含节点数据,下一指针)
- 定义链表域类(包含插入,删除,打印输出等)
话不多说上代码一看就明白~
头文件.h
#pragma once
#include<iostream>
using namespace std;
class List; 申明链表
class ListNode //节点
{
public:
friend class List; 定义友元(测试用,尽量不要申明友元,会破坏程序的封装性)
private:
int data; 节点数据
ListNode* next; 指向下一节点的指针
ListNode(int element); 构造函数 i
};
class List //定义链表
{
public:
List() { first = 0; }; //初始化指向第一个的指针为零
void Insert(); 插入
void Delet(); 删除
void print(); 打印输出
int ListSize(); 返回大小
void ListMenu();//菜单
private:
ListNode* first;
};
ListNode::ListNode(int element)
{
data = element;
next = NULL;
}
void List::Insert()//插入
{
cout << "请选择插入模式:" << endl;
cout << "1、单插" << endl;
cout << "2、多插(3)" << endl;
int k,w;
cin >> k;
if (k == 1)
{
cin >> w;
ListNode* pid = new ListNode(w);
pid->next = first;
first = pid;
}
else if (k == 2)
{
for(int i = 0;i<=3;++i)
{
if (i)
{
cout << "请输入要插入的数:" << endl;
cin >> w;
ListNode* pid = new ListNode(w);
pid->next = first;
first = pid;
}
}
cout << "已完成插入,即将退出插入环节!" << endl;
}
}
void List::print()
{
for (ListNode* pid = first; pid; pid = pid->next)
{
cout << pid->data << " ";
if (pid->next)cout << "->";带->输出
}
cout << endl;
}
void List::Delet()
{
int type;
cin >> type;
ListNode* pid = 0;//前一个
ListNode* pid2;
for (pid2 = first; pid2 && pid2->data != type;
pid = pid2, pid2 = pid2->next);
if (pid2)
{
if (pid) pid->next = pid2->next;
else first = first->next;
delete pid2;
}
}
int List::ListSize()
{
ListNode* pid = first;
int i = 0;
while(pid)
{
++i;
pid = pid->next;
}
return i;
}
void List::ListMenu()
{
cout << "--------------单链表操作菜单----------------" << endl;
cout << "--------------------------------------------" << endl;
cout << " (1)头插法 \n";
cout << " (*)尾插法 \n";
cout << " (*)随插法 \n";
cout << " (2)删除节点数据 \n";
cout << " (4)获取链表长度 \n";
cout << " (3)打印链表 \n";
cout << " (0)退出 \n";
cout << "--------------------------------------------" << endl;
cout << "请输入你的选择:" << endl;}
主函数.cpp
#include<iostream>
#include"单链表.h"
using namespace std;
int main(){ List pid;
while (true)
{
pid.ListMenu();
int select;
cin >> select;
switch (select)
{
case 1:
pid.Insert();
cout << "请输入要插入的数:" << endl;
system("pause");
system("cls");
break;
case 2:
pid.Delet();
cout << "请输入要删除的数:" << endl;
system("pause");
system("cls");
break;
case 3:
pid.print();
cout << "打印链表如下:" << endl;
system("pause");
system("cls");
break;
case 4:
cout << "链表大小为:"<<pid.ListSize() << endl;
system("pause");
system("cls");
break;
case 0:
cout << "欲穷千里目,更上一层楼" << endl;
cout << "希望此次你有所收获!" << endl;
system("pause");
system("cls");
return 0;
break;
default:
cout << "输入有误,请从新输入" << endl;
system("pause");
system("cls");
break;
}
}
return 0;
}
运行结果如下:
最后总结一下:
单链表的插入与删除是比数组快的,因为它不是连续存储的空间,只要改变指针的指向可以间接达到效果,除了这个优点链表好像一无是处,相对于实践运用数组要比链表更实用(它们的优缺点前面提到了就不多说了),链表每插入都需要申请额外空间,比较吃力(外加浪费系统资源)所以用的到的地方很少。