双循环链表根据查询次数非递增排序

本文介绍了一个使用双向循环链表实现的数据结构,该结构在每次元素定位后更新节点频率,并按频率非递减排序。通过C++代码演示了如何构建链表,插入元素,定位元素并调整其位置,确保链表始终保持有序状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
双向循环链表
新增freq
每进行一次locate操作,freq增1
并按照freq非递增排序

输入:1 2 3 4 5 -1 
*/
#include <iostream>
#include <malloc.h>
using namespace std;
const int FLAG = -1;

typedef struct DNode{
	int data;
	struct DNode *prior, *next;
	int freq;
}DNode, *DLinkList;

DLinkList List_Insert(DLinkList &L) {
	DLinkList s, p=NULL; 
	int x;
	L = (DLinkList)malloc(sizeof(DNode));
	L->next = L->prior = L;
	p = L;
	while(cin>>x && x!=FLAG) {
		s = (DLinkList)malloc(sizeof(DNode));
		s->data = x;
		s->freq = 0;
		
		s->next = p->next;
		p->next = s;
		L->prior = s;
		s->prior = p;
		p = s;
	}
	return L;
}

void listSort(DLinkList &L, DLinkList p){	//根据freq非递增排序
	DLinkList p1 = L->next;
	while(p1->freq > p->freq)	//要插入到p1的前面 
		p1 = p1->next;
		
	DLinkList t1 = p->prior;
	DLinkList t2 = p->next;
	t1->next = t2;
	t2->prior = t1;
	
	p1->prior->next = p;
	p->next = p1;
	p->prior = p1->prior;
	p1->prior = p;
}

void locate(DLinkList &L, int data){	//找元素 
	//非空判断
	if(L->next == L)
		return;
	DLinkList p = L->next;
	while(p != L){
		if(p->data == data){
			p->freq += 1;
			break;
		}
		p = p->next;
	}
	listSort(L, p);
}

void printList(DLinkList L){
	DLinkList p = L->next;
	while(p != L){
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}

void printList1(DLinkList L){
	DLinkList p = L->prior;
	while(p != L){//system("pause") ;
		cout << p->data << " ";
		p = p->prior;
	}
	cout << endl;
	system("pause");
}

int main(){
	DLinkList L;
	List_Insert(L);
	printList(L);

	locate(L, 5);
	printList(L);
	
	locate(L, 4);
	printList(L);
	
	locate(L, 5);
	printList(L);
	
	locate(L, 3);
	printList(L);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值