对于初学者,链表很麻烦
细化分有这么几点:
1.定义结点的结构体,以及单链表的类
2.初始化单链表
3.插入函数
4.删除函数
5.清空链表
6.销毁链表
代码如下:读者自行理解:
#include<iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkeListt {
private:
Node* head;
int len;
public:
//初始化
void Init() {
head = new Node;
head->next = NULL;
len = 0;
}
//输出
void Output() {
cout << "链表的长度为:" << len << endl;
if (len > 0) {
cout << "内容:" << endl;
Node* p = head->next;
for (int i = 0; i < len; i++) {
cout << p->data << ".";
p = p->next;
}
cout << endl;
}
}
//插入 pos:1-(n+1)
void Insert(int pos,int value) {
//定位指针p指向pos的上一个结点
Node* p = head;//头结点
for (int i = 0; i < pos - 1; i++) {
p = p->next;
}
//分配q结点并赋值
Node* q = new Node;
q->data = value;
q->next = NULL;
//插入
q->next = p->next;
p->next = q;
//len自增
len++;
}
//返回len的长度
int Getlen() {
return len;
}
//删除 pos:1-n
void Delete(int pos,int *value) {
//定位指针p指向pos的上一个结点
Node* p = head;//头结点
for (int i = 0; i < pos - 1; i++) {
p = p->next;
}
//q指向删除的结点
Node* q = p->next;
//删除
p->next = q->next;
//返回值
*value = q->data;
delete q;
len--;
}
//清空链表
void Clear()
{
int num = len;
if (num > 0) {
int temp;
//循环删除
for (int i = 0; i < num; i++) {
Delete(1, &temp);
}
}
}
//判断链表是否为空
bool isEmpty() {
return (len == 0) ? true : false;
}
//销毁
void Destroy() {
//判断是否为空,非空则清除链表
if (!isEmpty()) {
Clear();
}
//最后把头指针释放
delete head;
}
};
int main()
{
LinkeListt myself;
myself.Init();
myself.Output();
for (int i = 1; i <= 100; i++) {
myself.Insert(myself.Getlen()+1, i);
}
myself.Output();
int temp;
for (int i = 1; i <= 50; i++)
{
myself.Delete(i+1, &temp);
cout << "Delete:" << temp << endl;
}
myself.Output();
myself.Destroy();
}