头文件(.h)
#include<iostream>
using namespace std;
class Node
{
public:
int _data;
Node* next;
Node()
{
next = nullptr;
}
};
class List
{
private:
Node *head;
public:
List(); //链表逆置
void Create(); //创建链表
void Display()const; //显示链表
~List(); //销毁链表
int getlen() const; //获取链表长度
bool isEmpty() const; //判断链表是否为空
bool Find(const int e) const; //在链表中查找某个值
Node* GetNode(int i) const; //返回第i个节点
void Insert(int i, const int e); //在第i个位置插入元素e
void Delete(const int e); //删除一个元素e
void Reverse();
};
下面就源文件(.cpp)
#include"List.h"
List::List()//初始化链表
{
head = new Node();
head->next = nullptr;
}
void List::Create()//创建链表
{
Node *p, *q;
p = head;
q = new Node();
cout << "请输入数值(按Ctrl+z结束)" << endl;
while (cin >> q->_data)
{
p->next = q;
p = q;
q = new Node();
}
}
void List::Display()const
{
Node *p;
p = head->next;
while (p)
{
cout << p->_data<<" ";
p = p->next;
}
cout << endl;
}
List::~List()
{
Node *p;
while (head)
{
p = head->next;
delete head;
p = head;
}
}
int List::getlen()const
{
int len = 0;
Node *p = head->next;
while (p)
{
len++;
p = p->next;
}
return len;
}
bool List::isEmpty()const
{
return(head->next == nullptr);
}
bool List::Find(const int e)const
{
Node *p;
p = head->next;
while (p)
{
if (p->_data == e)
return true;
p = p->next;
}
return false;
}
Node* List::GetNode(int i) const
{
if (i<0 || i>getlen())
{
return false;
}
Node *p = head;
while (p&&i)
{
p = p->next;
i--;
}
return p;
}
void List::Insert(int i, const int e)
{
Node *p;
Node *node = new Node();
node->_data = e;
if (i == 1)
{
node->next = head->next;
head->next = node;
}
else
{
p = GetNode(i-1);
if (i == getlen())
{
p->next = node;
}
else
{
node->next = p->next;
p->next = node;
}
}
}
void List::Delete(const int e)
{
if (!Find(e))
{
cout << "没有此数据" << endl;
return;
}
Node*p = head;
Node*q = head->next;
while (q)
{
if (q->_data == e)
{
break;
}
p->next = q;
q = q->next;
}
p->next = q->next;
return;
}
void List::Reverse()//逆置单链表
{
if (isEmpty())
{
cout << "该链表为空" << endl;
return;
}
Node*p, *q;
int len = getlen();
int i = 1;
int j = len;
while (i < j)
{
p = GetNode(i);
q = GetNode(j);
int tmp = p->_data;
p->_data = q->_data;
q->_data = tmp;
i++;
j--;
}
}
最后就是测试文件
#include"List.h"
int main()
{
List* link = new List();
link->Create();
link->Display();
cout << link->getlen() << endl;
cout << link->isEmpty() << endl;
cout << link->Find(3) << endl;
link->Reverse();
link->Display();
/*try
{
cout << (link->GetNode(10))->_data << endl;
}
catch (int)
{
cout << "所要获取的节点位置超出链表范围" << endl;
}
link->Insert(1, 888);
link->Insert(3, 999);
link->Delete(6);
link->Display();
link->Reverse();
link->Display();
system("pause");*/
return 0;
}
当然这个单链表从时间复杂度来看,是非常垃圾的,这里就不做评价了。