|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<stdio.h>
- #include<stdlib.h>
- typedef struct list{
- struct list *prior;
- int data;
- int freq;
- struct list *next;
- }List;
- void CreatList(List *&L,int a[],int n)
- {
- List *s,*r;
- int i;
- L=(List *)malloc(sizeof(List));
- L->prior=L->next=NULL;
- r=L;
- for(i=0;i<n;i++)
- {
- s=(List *)malloc(sizeof(List));
- s->data=a[i];
- s->freq=0;
- r->next=s;s->prior=r;
- r=s;
- }
- r->next=NULL;
- }
- void printf(List *&L)
- {
- List *p=L->next;
- while(p!=NULL)
- {
- printf("%d ",p->data);
- p=p->next;
- }
- printf("\n");
- p=L->next;
- while(p!=NULL)
- {
- printf("%d ",p->freq);
- p=p->next;
- }
- printf("\n");
- }
- bool locatenode(List *&h,int x)
- {
- List *t,*p;
- p=h;
- for(h=h->next;h;h=h->next)
- {
- if(h->data==x)
- break;
- }
- if(h==NULL)
- return(false);
- else
- {
- h->freq++;
- for(t=h->prior;t!=p&&t->freq<=h->freq;t=t->prior);
- h->prior->next=h->next;
- if(h->next!=NULL)
- {
- h->next->prior=h->prior;
- }
- h->next=t->next;
- h->next->prior=h;
- t->next=h;
- h->prior=t;
- return(true);
- }
- }
- int main()
- {
- int a[5]={1,2,3,4,5};
- List *L;
- CreatList(L,a,5);
- printf(L);
- printf("\n");
- locatenode(L,4);
- printf(L);
- }
复制代码
怎么修改
按C语言给你改了
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- typedef struct list {
- struct list *prior, *next;
- int data, freq;
- } List;
- void CreatList(List **L, int a[const], int n) {
- struct list *h = NULL, **pn = L;
- for(size_t i = 0; i < n; ++i) {
- *pn = malloc(sizeof(**pn));
- (*pn)->prior = h;
- (*pn)->next = NULL;
- (*pn)->data = a[i];
- (*pn)->freq = 0;
- h = *pn;
- pn = &h->next;
- }
- }
- void print(const List *L) {
- for(const List *i = L; i; i = i->next) {
- printf("%d ", i->data);
- }
- puts("");
- for(const List *i = L; i; i = i->next) {
- printf("%d ", i->freq);
- }
- puts("");
- }
- bool locatenode(List *L, int x) {
- for(List *i = L; i; i = i->next) {
- if(i->data != x) continue;
- ++i->freq; return true;
- }
- return false;
- /*
- 这是在做什么?
- for(t = h->prior; t != p && t->freq <= h->freq; t = t->prior)
- ;
- h->prior->next = h->next;
- if(h->next != NULL) {
- h->next->prior = h->prior;
- }
- h->next = t->next;
- h->next->prior = h;
- t->next = h;
- h->prior = t;
- */
- }
- // 有始有终,有借有还
- // 好不好?
- void free_list(List *L) {
- if(!L) return;
- free_list(L->next);
- free(L);
- }
- int main(void) {
- int a[5] = {1, 2, 3, 4, 5};
- List *L;
- CreatList(&L, a, 5);
- print(L);
- printf("%d\n", locatenode(L, 4));
- print(L);
- free_list(L);
- return 0;
- }
复制代码
|
|