第2章 线性表的链式表示
综合应用题 第20题
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct dnode {
ElemType data;
int len,freq;
struct dnode *prior,*next;
}DNode, *DLinkList;
DLinkList DLinkListInit() {
DNode *L;
L = (DNode *)malloc(sizeof(DNode));
if (L == NULL) {
cout<<"申请内存空间失败\n";
exit(0);
}
L->next =NULL;
L->prior=NULL;
L->len=0;
return L;
}
DLinkList DLinkListCreatT(ElemType *a, int n) {
DNode *L;
L = DLinkListInit();
DNode *r=L,*p;
for (int i = 0; i < n; i++){
p = (DNode *)malloc(sizeof(DNode));
if (p == NULL) {
cout<<"申请内存空间失败\n";
exit(0);
}
p->data = a[i];
p->freq = 0;
p->next = r->next;
p->prior=r;
r->next = p;
r=p;
L->len++;
}
return L;
}
DLinkList Locate(DLinkList &L,ElemType x)
{
DNode *p=L->next,*q;
while(p&&p->data!=x)
{
p=p->next;
}
if(!p)
{
cout<<"没有找到!"<<endl;
exit(0);
}
else{
p->freq++;
p->next->prior=p->prior;
p->prior->next=p->next;
q=p->prior;
while(q!=L&&q->freq<=p->freq)
{
q=q->prior;
}
p->next=q->next;
q->next->prior=p;
p->prior=q;
q->next=p;
}
return p;
}
int main() {
DLinkList list1,start;
int array1[5] = { 2, 4, 3 , 4 , 2 };
cout<<"输出单链表的数据:"<<endl;
list1=DLinkListCreatT(array1,5);
for (start = list1->next; start != NULL; start = start->next) {
cout<<start->data<<" freq:"<<start->freq<<endl;
}
cout<<endl;
Locate(list1,3);
for (start = list1->next; start != NULL; start = start->next) {
cout<<start->data<<" freq:"<<start->freq<<endl;
}
cout<<endl;
return 0;
}
|