spy 发表于 2015-3-27 17:03:05

魔术师发牌问题的解决

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

struct Node
{
        int data;
        struct Node *next;
};

void InitList(struct Node **, struct Node **, int);
void CreateList(struct Node *, struct Node *, struct Node **, struct Node **, int);
void ListTraverse(struct Node *, struct Node *);

void main()
{
        struct Node *head, *rear, *r, *s;
        int n;
        printf("请输入黑桃牌的张数: ");
        scanf("%d", &n);
        putchar('\n');
        InitList(&head, &rear, n);
        CreateList(head, rear, &r, &s, n);
        ListTraverse(r, s);
}

void InitList(struct Node **head, struct Node **rear, int n)
{
        struct Node *p, *q;
        int i, j;
        *head = (struct Node *)malloc(sizeof(struct Node));
        p = *head;
        for(i=1;i<=n;i++)
        {
                j = 1;
                q = (struct Node *)malloc(sizeof(struct Node));
                p->next = q;
                p = q;
                q->data = 0;
        }
        p->next = (*head)->next;
        *rear = p;
}

void CreateList(struct Node *head, struct Node *rear, struct Node **r, struct Node **s, int n)
{
        struct Node *p=head->next, *q=rear, *t;
        int i=1, j;
        InitList(r, s, n);
        t = (*r)->next;
        while(p!=p->next)
        {
                j= 1;
                while(j%i)
                {
                        p = p->next;
                        while(t->next->data!=0)
                        {
                                t = t->next;
                        }
                        t = t->next;
                        q = q->next;
                        j++;
                }
                printf("黑桃%2d    ", i);
                t->data = p->data = i++;
                q->next = p->next;
                free(p);
                p = q->next;
                while(t->next->data!=0)
                {
                        t = t->next;
                }
                t = t->next;
        }
        t->data = i;
        printf("黑桃%2d    \n\n", i);
}

void ListTraverse(struct Node *r, struct Node *s)
{
        struct Node *p = r;
        printf("**********扑克牌应该按如下顺序排列:**********\n\n");
        while(p!=s)
        {
                p = p->next;
                printf("黑桃%2d    ", p->data);
        }
        printf("\n\n");
}

zhang99844 发表于 2015-9-5 09:03:11

虽然我看不懂在说什么。但是还是要顶一下
页: [1]
查看完整版本: 魔术师发牌问题的解决