最近在看b站上一个视频,学习数据结构,了解链表后发现所有的视频都不是面向对象方式,然后就好奇,面向对象应该如何实现链表,是否会更方便。于是自己动手试了一下,发现可以将链表的一系列操作封装,便以使用。
1.运行结果
1)首先插入6个元素
2)删除结点
3)打印删除后的链表
4)反转链表
2.源码
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
class list
{
public:
Node* head; //头节点地址
int len; //链表长度
public:
list()
{
len = 0;
head = new Node;
head->next = NULL;
}
~list()
{
delete[]head;
}
void Insert(int n)
{
Node* head1 = head;
Node* temp = new Node;
temp->next = NULL;
temp->data = n;
len++;
if (head->next == NULL)
{
head->next = temp;
return;
}
while (head1->next != NULL)
{
head1 = head1->next;
}
head1->next = temp;
}
void Print()
{
cout << "共有" << len << "个结点\t";
Node* head1 = NULL;
head1 = head->next;
while (head1 != NULL)
{
cout << head1->data << " ";
head1 = head1->next;
}
cout << endl;
}
void Delete()
{
int n = 0;
while (n <= 0 || n > len)
{
cout << "删除第几个元素?";
cin >> n;
}
Node* head1 = head;
for (int i = 0; i < n - 1; i++)
{
head1 = head1->next;
}
Node* temp = head1->next;
head1->next = temp->next;
delete temp;
len--;
}
void Reverse()
{
if (head->next == NULL || head->next->next == NULL)
{
return;
}
Node* t = NULL;
Node* p = head->next;
Node* q = p->next;
while (q != NULL)
{
t = q->next;
q->next = p;
p = q;
q = t;
}
head->next->next = NULL;
head->next = p;
}
};
int main()
{
list list1;
list1.Insert(1);
list1.Insert(2);
list1.Insert(3);
list1.Insert(4);
list1.Insert(5);
list1.Insert(6);
list1.Print();
list1.Delete();
list1.Print();
list1.Reverse();
list1.Print();
}