题目:
设有一个双链表h,每个结点中除了有prior、data和next几个域以外,还有一个访问频度域freq,在链表被启用之前,其值均初始化为零。每当进行 Locatenode(h,x)运算时,令元素值为x的结点中freq域的值加1,并调整表中结点的次序,使其按访问频度的递减次序排列,以便使频繁访问的结点总是靠近表头。试写一个符合上述要求的 Locatenode运算的算法。
实现代码:
#include<iostream>
using namespace std;
typedef int elem;
#include<malloc.h>
typedef struct dnode
{
elem data;
elem freq;
struct dnode* prior, * next;
} doublenode;
void initlist(doublenode*& L)
{
L= (doublenode*)malloc(sizeof(doublenode));
if (L == NULL)
{
return;
}
L->prior = NULL;
L->next = NULL;
L->freq = 0;
return ;
}//为创建的双链表进行初始化
void deletedouble(doublenode* p)
{
if (p == NULL)
{
return ;
}
doublenode* q = p->next;
if (q == NULL)
{
return ;
}
p->next = q->next;
if (q->next != NULL)
{
q->next->prior = p;
}
free(q);
return ;
}//删除某一结点
void destorylists(doublenode*& L)
{
doublenode* s = L->next;
while (s!= NULL)
{
deletedouble(s);
s = s->next;
}
free(L);
}//销毁双链表
void locatenode(doublenode*& L, elem x)
{
doublenode* p = L->next;
doublenode* s = NULL;
while (p != NULL)
{
if (p->data == x)
{
s = p;
p->freq++;
p->prior->next = p->next;
p->next->prior = p->prior;
break;
}
p = p->next;
}
if (s != NULL)
{
doublenode*pp = L;
while (pp->next != NULL)
{
if(pp->next->freq <= s->freq)
{
s->next=pp->next;
pp->next->prior=s;
s->prior=pp;
pp->next=s;
break;
// s->next=pp->next;
// pp->prior=s;
// s->prior=pp;
//pp->next=s;
// break;
// s->next = pp->next;
// pp->next->prior = s;
// s->prior = pp;
// pp->next = s;
// break;
}
pp=pp->next;
}
}
}//频度+1
void display(doublenode* L)
{
doublenode* s = L->next;
while (s != NULL)
{
cout << s->data << " ";
s = s->next;
}
cout << "\n";
s = L->next;
while (s != NULL)
{
if(s->data<10)
cout << s->freq << " ";
else
cout<<s->freq<<" ";
s = s->next;
}
cout << "\n";
}
int main()
{
doublenode* L1;
initlist(L1);
doublenode* s, * p = L1;
initlist(s);
for (int i = 1; i <=20; i++)
{
s->data = i;
s->freq = 0;
p->next = s;
s->next = NULL;
s->prior = p;
p = p->next;
s = (doublenode*)malloc(sizeof(doublenode));
}
locatenode(L1, 15);
locatenode(L1, 6);
locatenode(L1, 11);
locatenode(L1, 16);
locatenode(L1, 6);
locatenode(L1, 15);
locatenode(L1, 11);
locatenode(L1, 8);
display(L1);
destorylists(L1);
free(s);
return 0;
}