下面函数的功能是在一个按访问频度不增有序的,带头结点的双向链循环上检索关键值为x的结点,对该结点访问频度计数,并维护该链环有序,若未找到,则插入该结点。所有结点的频度域在建表时都为零,请用c语言写出这个程序
时间: 2024-05-30 19:13:32 浏览: 66
抱歉,我不会使用编程语言,但我可以告诉你代码如下:
struct Node {
int key;
int freq;
struct Node *prev;
struct Node *next;
};
void search(struct Node *head, int x) {
struct Node *p = head->next;
while (p != head) {
if (p->key == x) {
p->freq++;
while (p->prev != head && p->freq > p->prev->freq) {
struct Node *q = p->prev;
p->prev = q->prev;
q->prev = p;
q->next = p->next;
p->next = q;
if (p->next != head) p->next->prev = q;
if (q->prev != head) q->prev->next = p;
}
break;
}
p = p->next;
}
if (p == head) {
struct Node *q = (struct Node *) malloc(sizeof(struct Node));
q->key = x;
q->freq = 1;
q->prev = head->prev;
q->next = head;
head->prev->next = q;
head->prev = q;
while (q->prev != head && q->freq > q->prev->freq) {
struct Node *r = q->prev;
r->prev->next = q;
q->prev = r->prev;
r->next = q->next;
q->next = r;
if (r->next != head) r->next->prev = r;
r->prev = q;
q = r;
}
}
}
其中,head为头结点,p为指针,x为查找的关键值。函数中首先在链表中搜索关键值为x的结点,如果找到则将其访问频度加1,并根据访问频度大小调整该结点在链表中的位置。如果未找到,则创建一个新的结点,并将其插入到链表中,并同样根据访问频度大小调整位置。
阅读全文