uva 127 - "Accordian" Patience

/*

写一次链表,又回想起来很多东西,

注意:创建链表时一定要把节点中的所有指针相应地赋值,否则程序很容易崩掉,比如last指针的建立

*/

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct _stack
{
 int top;
 char suit[60];
 char rank[60];
 struct _stack *last;
 struct _stack *next;
}stack;
char card[60][3];
stack *create()
{
    int i;
    stack *head,*now,*_new;
    head=(stack *)malloc(sizeof(stack));
    now=head;
    now->top=0;
    now->suit[0]=card[0][0];
    now->rank[0]=card[0][1];
    head->last=NULL;
    for(i=1;i<52;i++)
    {
        _new=(stack *)malloc(sizeof(stack));
        now->next=_new;
        _new->last=now;
        now=_new;
        now->top=0;
        now->suit[0]=card[i][0];
        now->rank[0]=card[i][1];
    }
    now->next=NULL;
    return head;
}


stack *move(stack *p1,stack *p2)
{
    stack *p,*_p;
    p2->top++;
    p2->suit[p2->top]=p1->suit[p1->top];
    p2->rank[p2->top]=p1->rank[p1->top];
    p1->top--;
    if(p1->top==-1)
    {
        p=p1->last;
  _p=p1->next;
        p->next=_p;
  if(_p!=NULL)
  _p->last=p;
        free(p1);
    }
 return p2;
}


int main()
{
    stack *head,*p,*p3,*p1;
 int i,remain;
 while(1)
 {
  scanf("%s",card[0]);
  if(strcmp(card[0],"#")==0)
   break;
  for(i=1;i<52;i++)
   scanf("%s",card[i]);
        head=create();
       
  remain=0;
        p=head;
            while(p!=NULL)
            {
                p3=p;
                for(i=0;i<3&&p3!=NULL;i++)
                p3=p3->last;
                if(p3!=NULL)
                {
     if(p3->suit[p3->top]==p->suit[p->top]||p3->rank[p3->top]==p->rank[p->top])
                    {
      p=move(p,p3);
                        continue;
     }
                }
    p1=p->last;
                if(p1!=NULL)
               {
     if(p1->suit[p1->top]==p->suit[p->top]||p1->rank[p1->top]==p->rank[p->top])
     {
                        p=move(p,p1);
                        continue;
     }
               }
               p=p->next;
             }
        p=head;
        while(p!=NULL)
        {
   remain++;
            p=p->next;
        }
  if(remain>1)
    printf("%d piles remaining:",remain);
  else
   printf("%d pile remaining:",remain);
  p=head;
  while(p!=NULL)
  {
   printf(" %d",p->top+1);
   p=p->next;
  }
        printf("\n");
 }
 return 0;
}

你可能感兴趣的:(uva)