设有一个双链表h,每个结点中除了有prior、data和next几个域以外,还有一个访问频度域freq,在链表被启用之前,其值均初始化为零。每当进行 Locatenode(h,x)运算时,令元素值为x

题目:

设有一个双链表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;
}

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值