题目:输入数字m,n。
接着输入m个字符,以双向链表形式输入。链表除了有node *pre,*next,int num,还有char s,初始化num为0;
再输入n个字符,如果字符等于list->s,则list->num++。
将链表按num非递增顺序输出。
#include<stdio.h> #include<stdlib.h> typedef struct node{ int num; struct node *pre,*next; char s; }node; node* init(int x){ char a; node *head,*p,*q; head=(node*)malloc(sizeof(node)); head->pre=NULL; q=head; while(x--){ p=(node*)malloc(sizeof(node)); while(1){ a=getchar(); if(a!=' '&&a!='\n'){ break; } } p->s=a; p->num=0; p->pre=q; q->next=p; q=p; } q->next=NULL; return head; } node* locate(node *head,int x,int y){ node *p,*q; char a; int i; p=head->next; while(x--){ while(1){ a=getchar(); if(a!=' '&&a!='\n'){ break; } } while(p){ if(p->s == a){ (p->num)++; } p=p->next; } p=head->next; } for(i=0;i<y;i++){ p=head->next; q=p; while(p){ if(q->num < p->num){ q=p; } p=p->next; } if(i<y-1){ printf("%c ",q->s); } else{ printf("%c\n",q->s); } if(q->pre==NULL){ head->next=q->next; q->next->pre=head; } else if(q->next==NULL){ q->pre->next=NULL; } else{ q->pre->next=q->next; q->next->pre=q->pre; } free(q); } return head; } node* output(node *head){ node *p; p=head->next; while(p){ if(p->next==NULL){ printf("%c\n",(p->s)); } else{ printf("%c ",(p->s)); } } } int main(){ int m,n; node *head; scanf("%d%d",&m,&n); head=init(m); head=locate(head,n,m); output(head); return 0; }