双向链表,增加一个访问频度,使访问频度高的靠近头结点

#include<stdio.h>
#include<string.h>
#include<malloc.h>
typedef struct node 
{
int freq;//频度
int data;
struct node* prior;//指向前一个节点的指针
struct node* next;//指向后一个节点的指针
}Node;
/*创建链表*/
void createlist(Node** phead,int str[],int len)
{
Node *temp;
int i;

/*初始化头结点*/
(*phead)->next=NULL;
(*phead)->prior=NULL;
/*利用头插法插入节点*/
    for (i=0;i<len;i++)//这个地方会提示警告,你把i<strlen(str)改成(size_t)i<strken(str)就没警告
{
temp=(Node*)malloc(sizeof(Node));
temp->data=str[i];
temp->freq=0;
temp->next=(*phead)->next;
if(temp->next)
temp->next->prior=temp;
temp->prior=(*phead);
(*phead)->next=temp;
}
}
/*对链表进行遍历输出*/
void traverselist(Node *phead)
{
Node *temp;
for (temp=phead->next;temp!=NULL;temp=temp->next)
{
printf("%d ",temp->data);
}
printf("\n");
}
/*查找节点元素,找到则freq++*/
void locate(Node* phead,int ch)
{
Node *temp,*p;
p=phead;
/*从头结点开始遍历链表,看是否存在ch这个节点*/
for (phead=phead->next;phead!=NULL;phead=phead->next)
{
if(phead->data==ch)
break;
}
/*空链表或者没找到,退出该函数*/
if(phead==NULL)
        return;
/*找到*/
else
{
phead->freq++;
for(temp=phead->prior;temp!=p&&temp->freq<=phead->freq;temp=temp->prior)

phead->prior->next=phead->next;
if(phead->next)
phead->next->prior=phead->prior;
phead->next=temp->next;
phead->next->prior=phead;
temp->next=phead;
phead->prior=temp;
return ;

}
}
int main()
{
Node* head=(Node*)malloc(sizeof(Node));
int shuzu[60];
bool tag=true;
int len,m;
char ch;
printf("请输入节点个数:");
scanf("%d",&len);
for (int i=0;i<len;i++)
{
scanf("%d",&shuzu[i]);
}
createlist(&head,shuzu,len);
      traverselist(head);//因为利用头插法创建的链表所以先输入的节点是在最后面
    while (tag)
    {
printf("\n请输入要查找的元素:");
scanf("%d",&m);
getchar();
locate(head,m);
traverselist(head);
printf("是否继续查找,继续输入y,否则输入n:");
      scanf("%c",&ch);
   if(ch=='n')
tag=false;
}
   
return 0;
}

转载于:https://my.oschina.net/u/553254/blog/98223

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值