代码实现效果如下:
#include<iostream>
using namespace std;
//双向链表
class Node
{
public:
int data;
Node* prior;
Node* next;
};
class DulLink
{
public:
DulLink();
~DulLink();
void CreatLink(); //创建
void ShowLink(); //显示
void FindLink(); //查找
void InsertLink(); //插入元素
void ValueDeleLink(); //删除指定数值
private:
Node* head;
int length;
};
DulLink::DulLink()
{
head = new Node;
head->prior = head->next = head;
length = 0;
}
void DulLink::CreatLink()
{
Node* p = head->prior;
Node* pnew = new Node;
cout << "输入数值:" << " ";
cin >> pnew->data; cout << endl;
head->prior = pnew;
pnew->next = head;
p->next = pnew;
pnew->prior = p;
p = head->prior;
length++;
}
void DulLink::ShowLink()
{
Node* p = head->next;
while (p != head) {
cout << "链表元素为:" << p->data << " ";
p = p->next;
}
cout << endl;
}
void DulLink::FindLink()
{
cout << "输入查询数值:" << " ";
int e = 0; cin >> e; cout << endl;
int k = 1; Node* p = head->next;
while (p != head && p->data != e) {
p = p->next;
k++;
}
if (p == head) {
cout << "不存在!" << endl;
}
else {
cout << "位置为:" << k << endl;
}
}
void DulLink::InsertLink()
{
cout << "输入插入位置:" << " ";
int k = 0; cin >> k; cout << endl;
Node* ptemp = head;
if (k > 0 && k <= length+1) {
for (int i = 0; i < k; i++) {
ptemp = ptemp->next;
}
Node* pnew = new Node;
cout << "输入数值: " << " ";
cin >> pnew->data; cout << endl;
pnew->next = ptemp;
(ptemp->prior)->next = pnew;
pnew->prior = ptemp->prior;
ptemp->prior = pnew;
length++;
}
}
void DulLink::ValueDeleLink()
{
int e = 0; int k = 1;
Node* p = head->next;
cout << "输入删除值:" << " ";
cin >> e; cout << endl;
while (p != head && p->data != e) {
p = p->next;
k++;
}
if (p == head) {
cout << "无此值!" << endl;
}
else {
cout << "已删除元素:" << p->data << " 位置为:" << k << endl;
p->prior->next = p->next;
p->next->prior = p->prior;
delete p; p = NULL;
}
}
DulLink::~DulLink()
{
Node* p = head->next;
while (p != head) {
p = p->next;
delete p->prior;
}
delete head;
head = p = NULL;
}
int main()
{
DulLink s;
s.CreatLink();
s.CreatLink();
s.CreatLink();
s.ShowLink();
s.InsertLink();
s.ShowLink();
s.ValueDeleLink();
s.ShowLink();
s.FindLink();
system("pause");
return 0;
}