数据结构理论课noj(6) LOCATE操作

本文介绍了一个使用双向链表实现的字符缓存系统,该系统能够通过更新字符节点的频率来调整其在缓存中的位置,确保高频字符靠近头部以便快速访问。程序包括创建双向链表、插入节点、定位并更新节点频率等功能。

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

#include <stdio.h>
#include <stdlib.h>
#define MAXNUM 1e6
typedef struct DNODE
{
    char c;
    struct DNODE *prior ,*next;
    int freg;
}DNODE;

DNODE* create_list()
{
    DNODE *p = (DNODE*)malloc(sizeof(DNODE));
    p ->prior = NULL;
    p ->next = NULL;
    p->freg = MAXNUM;
    return p;
}

void insertDNode(DNODE *L,int m) //第一个节点要特殊插入
{
    DNODE *s=L->next;

    while(m--)
    {
        DNODE *p = (DNODE*)malloc(sizeof(DNODE));
        char c;
        do
        {
            scanf("%c",&c);
        }while(c == ' ' || c == '\n');
        p->c = c;
        p->freg = 0;
        p->next = s->next;
        p->prior = s;
        s->next = p;
        s = p;
    }
}
void printlist(DNODE *L)
{
    DNODE *p=L->next;
    while(p)
    {
        printf("%c ",p->c);
        p=p->next;
    }
}
void LOCATE(DNODE *L, char x)
{
    DNODE *p = L->next;
    while(p&& p->c!=x)
    {
        p = p->next;
    }
    if(p->c==x)
    {
        p->freg ++;
    }

    while(p->freg >p->prior->freg) //头节点不会被换掉,不用慌
    {
       char t=p->c;
       int tmp = p->freg;

       p->c = p->prior->c;
       p->freg = p->prior->freg;

       p->prior->c = t;
       p->prior->freg = tmp;

       p=p->prior;

    }

}
int main()
{
    int m,n;
    scanf("%d %d",&m,&n);
    DNODE *L = create_list();
    //第一个节点要特殊处理
    {
        char t;
        do
        {
            scanf("%c",&t);
        }while(t == ' ' || t == '\n');
        DNODE *p =(DNODE*)malloc(sizeof(DNODE));
        p->freg = 0;
        p->c = t;
        p->next =L->next;
        p->prior = L;
        L->next = p;
    }
    insertDNode(L,m-1);
    fflush(stdin);
    while(n--)
    {
        char x;
        do
        {
            scanf("%c",&x);
        }while(x == ' ' || x == '\n');

        LOCATE(L,x);
    }

    printlist(L);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哥手下留情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值