解题思路:
- 构建并初始化非循环双向链表;
- 数据域储存值和频度,让频度开始都为0
- 按值函数查找后所在结点频度加1。
- 所得结点和前面结点频度比较,如果频度大于等于前面结点频度,那么交换两个结点,否则不交换,位置不变。
- 当交换时,循环比较,直到所换位置在头节点后面或者和小于前面结点。
关键代码:
- 双链表的尾插法:
void begin(Node* head, Date a[], int n)
{
Node* rear = head;
for (int i = 0; i < n; ++i)
{
Node* s = new Node;
s->next = nullptr;
s->prior = nullptr;
s->date = a[i].date;
s->free = a[i].free;
rear->next = s;
s->prior = rear;
rear = s;
}
}
- 结点和前面结点的交换:
void begin(Node* head, Date a[], int n)
{
Node* rear = head;
for (int i = 0; i < n; ++i)
{
Node* s = new Node;
s->next = nullptr;
s->prior = nullptr;
s->date = a[i].date;
s->free = a[i].free;
rear->next = s;
s->prior = rear;
rear = s;
}
}
- 按值查找:
Node *Locate(Node *L,int x)
{
Node *p= L->next;
while (p != nullptr && p->date != x)
p = p->next;
if( p->date!=x) return 0;
p->free=p->free+1;
while(1)
{
if (p->prior != L &&p->free >= p->prior->free)
change(p);
else break;
}
return p;
}
完整代码:
#include<iostream>
using namespace std;
struct Node {
int date;
int free;
Node* next = nullptr;
Node* prior = nullptr;
};
struct Date
{
int date;
int free;
};
void destroy(Node* head)
{
Node* p = head;
while (p)
{
Node* q = p;
p = p->next;
delete q;
}
}
void show(Node* t2)
{
if (t2 != nullptr)
{
cout << "初始数据为:" << endl;
t2 = t2->next;
while (t2 != nullptr)
{
cout << " " << t2->date << "(" << t2->free << ")";
t2 = t2->next;
}
cout << endl;
}
else
cout << "表中无数据" << endl;
}
void begin(Node* head, Date a[], int n)
{
Node* rear = head;
for (int i = 0; i < n; ++i)
{
Node* s = new Node;
s->next = nullptr;
s->prior = nullptr;
s->date = a[i].date;
s->free = a[i].free;
rear->next = s;
s->prior = rear;
rear = s;
}
}
void change(Node* L)
{
Node* p = L; Node* q = p->prior;
if (p->next != nullptr)
{
q->prior->next = p;
p->prior = q->prior;
q->next = p->next;
p->next->prior = q;
p->next = q;
q->prior = p;
}
else
{
p->prior = q->prior;
p->next = q;
q->prior->next = p;
q->prior = p;
q->next=nullptr;
}
}
Node *Locate(Node *L,int x)
{
Node *p= L->next;
while (p != nullptr && p->date != x)
p = p->next;
if( p->date!=x) return 0;
p->free=p->free+1;
while(1)
{
if (p->prior != L &&p->free >= p->prior->free)
change(p);
else break;
}
return p;
}
int main()
{
Date a[10];
for (int i = 0; i < 10; ++i)
{
a[i].date = i + 1;
a[i].free = 0;
}
Node* head = new Node;
head->next = head;
head->prior = head;
begin(head,a,10);
show(head);
Node* p = head->next->next;
Node* q = head->next;
while (1)
{
int x;
cout << "请输入需要查询的值:" << endl;
cin >> x;
Node *xx=Locate(head, x);
show(head);
cout <<"所查询的指针的地址为:" << xx << endl<<endl;
}
destroy(head);
return 0;
}
结果截图: