LOCATE操作(严2.38)
Time Limit: 3000ms, Memory Limit: 10000KB, Accepted: 265, Total Submissions: 768
Description
设有一个双向循环链表,每个结点中除有pre,data和next三个域外,还增设了一个访问频度域freq。在链表被起用之前,频度域freq的值均初始化为零,而每当对链表进行一次LOCATE(L,x)的操作后,被访问的结点(即元素值等于x的结点)中的频度域freq的值便增1,同时调整链表中结点之间的次序,使其按访问频度非递增的次序排列,以便始终保持被频繁访问的结点总是靠近表头结点。试编写符合上述要求的LOCATE操作的程序。
Input
第一行输入双向循环链表的节点数m和被访问的节点数n,
第二行输入双向循环链表各节点的值,
第三行依次输入被访问的节点。
Output
输出符合上述要求的双向循环链表。
输出经过n次LOCATE后的链表。
# include <iostream>
# include <cstdio>
# include <cmath>
# include <cctype>
# include <vector>
#include <string>
#include <algorithm>
using namespace std;
typedef struct node
{
node* pre;
node* next;
char data;
int freq;
}node,*Pnode;
Pnode head = new node;
void initial(Pnode P, char t);
void insertl(char t);
void arrangel(char t);
void initial1(Pnode head);
void outputl();
int main()
{
initial1(head);
int a, b;
cin >> a >> b;
while (a--)
{
char temp;
cin >> temp;
insertl(temp);
}
while (b--)
{
char temp;
cin >> temp;
arrangel(temp);
}
outputl();
}
void outputl()
{
Pnode q = head;
while (q->next != NULL)
{
q = q->next;
cout << q->data << " ";
}
}
void arrangel(char t)
{
Pnode q = head;
while (q->data != t)
{
q = q->next;
}
q->freq += 1;
if (q->pre != NULL)
{
while (q->freq > q->pre->freq)
{
Pnode m = new node;
Pnode q0 = q->pre;
m->pre = q0->pre;
m->next = q->next;
q->next = q0;
q0->pre = q;
q->pre = m->pre;
q->pre->next = q;
q0->next = m->next;
if (q0->next != NULL)
{
q0->next->pre = q0;
}
}
}
}
void insertl(char t)
{
Pnode q = head;
while (q->next!=NULL)
{
q = q->next;
}
Pnode p = new node;
initial(p,t);
p->pre = q;
p->next = q->next;
q->next = p;
}
void initial(Pnode P,char t)
{
P->data = t;
P->pre = NULL;
P->next = NULL;
P->freq = 0;
}
void initial1(Pnode P)
{
P->data = 0;
P->pre = NULL;
P->next = NULL;
P->freq = 99999999;
}