uva 133 The Dole Queue

//算法描述,构建一个双向循环链表,不需要不存放数据的头指针,按照prior指针遍历则认为是逆时针,按照next指针遍历则认为是顺时针

 

//prior是逆时针,next是顺时针
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct node)
int N,k,m;
struct node
{
    int num;
    struct node *prior,*next;
};
void print_link(struct node *L)
{
    struct node *p;
    p=L; printf("%d\n",p->num); p=p->prior;
    while(p!=L) {printf("%d\n",p->num);p=p->prior;}
    printf("***************************\n");
    p=L; printf("%d\n",p->num); p=p->next;
    while(p!=L) {printf("%d\n",p->num);p=p->next;}
    printf("***************************\n");
}

int main()
{
    struct node *L,*l1,*l2,*temp1,*temp2;  int i;  int flag,count;  int m1,m2;  
    while(scanf("%d%d%d",&N,&k,&m)!=EOF && N && k && m )
    {
        L=l1=(struct node*)malloc(LEN);  L->prior=L->next=NULL; L->num=1;
        for(i=2; i<=N; i++) 
        {
            l2=(struct node*)malloc(LEN); l2->num=i;
            l1->prior=l2; l2->next=l1; l2->prior=NULL; l1=l2;
        }
        l1->prior=L; L->next=l1; l1=L; l2=L->next;  count=0;  
//        printf("%d %d\n",l1->num,l2->num);  //print_link(L);
        flag=0;
        while(count<(N-2) )
        {
            for(i=1; i<k; i++)  l1=l1->prior;  m1=l1->num; 
            for(i=1; i<m; i++)  l2=l2->next;   m2=l2->num; 
            if(m1==m2)  
            {
                count++;  if(flag)  printf(",");  
                temp1=l1->prior;  temp2=l1->next;   temp1->next=temp2;  temp2->prior=temp1; 
                printf("%3d",l1->num); 
                free(l1);  l1=temp1; l2=temp2;
                flag=1;
            }
            else
            {
                count+=2;   if(flag) printf(",");  
                temp1=l1->prior;  temp2=l1->next;  temp1->next=temp2;  temp2->prior=temp1; 
                printf("%3d",l1->num); 
                free(l1);  l1=temp1;  if(l1==l2) l1=l1->prior;  //这个判断很重要否则会有BUG
                temp1=l2->prior;  temp2=l2->next;  temp1->next=temp2;  temp2->prior=temp1; 
                printf("%3d",l2->num); 
                free(l2);  l2=temp2;
                flag=1;
            }
        }

        if(count==(N-1))   //不能漏掉这种情况否则程序会奔溃掉
        {  if(flag) printf(",");  printf("%3d\n",l1->num);  continue;  }
        for(i=1; i<k; i++)  l1=l1->prior;  m1=l1->num; 
        for(i=1; i<m; i++)  l2=l2->next;   m2=l2->num;

        if(m1==m2)
        {
            if(flag) printf(",");  printf("%3d",l1->num); 
            l2=l1->prior; printf(","); printf("%3d",l2->num); printf("\n"); 
        }
        else 
        {
            if(flag) printf(",");  printf("%3d%3d\n",l1->num,l2->num); 
        }
        free(l1); free(l2);  
    }
    return 0;
}

 

 

posted @ 2012-10-05 22:23  Titanium  阅读(223)  评论(0编辑  收藏  举报