search

Home  >  Q&A  >  body text

c++ - 关于约瑟夫问题,哪错了

#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
    int data;
    struct Node *next;
}Node,*LinkList;
int zhuti(Linklist A)
{
    typedef struct Node *p,*q;
    int i;
    printf("输入报数上限\n");
    scanf("%d",&m);
    LinkList B;
    *B=(typedef struct Node*)malloc(sizeof(Node));
    B->next=NULL;
    p=A;
    q=B;
    while(p!=p->next)
    {
        for(i=1;i!=m;i++)
            p=p->next;
        q->next=p;
        q=q->next;
        p->next=p->next->next;
    }
    q->next=p;
    q=q->next;
    q->next=NULL;
    return (B);
}
LinkList shuchu(LinkList B)
{
    while(B!=NULL)
    {
        printf("%d,",B->date);
        B=B->next;
    }
}
void jianli(LinkList A)
{
    typedef struct Node *s;
    int i,n;
    printf("输入人数\n");
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        s=(Node*)malloc(sizeof(Node));
        s->date=i;
        s->next=A->next;
        A->next=s;
    }
}
int main()
{
    LinkList B;
    LinkList A;
    A=(LinkList)malloc(sizeof(Node));
    A->next=NULL;
    jianli(LinkList A);
    B=zhuti(Linklist A);
    shuchu(LinkList B);
    return 0;
}
阿神阿神2773 days ago437

reply all(1)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 14:41:51

    There are many problems with this code. It can be seen that I am a beginner. There are many grammatical errors in the application of structures. Here is a correct answer that was modified using this code.

    #include<stdio.h>
    #include<malloc.h>
    
    typedef struct LNode {
        int data;
        struct LNode *next;
    }LNode;
    
    
    LNode* MainPart(LNode* A)
    {
        LNode *p=A, *q;
        int i, m;
    
        printf("数到几的人出局?: ");
        scanf("%d", &m);
    
        while(p!=p->next)
        {
            for(i=1; i!=m; i++)
                p=p->next;
    
            q=p->next;
            p->next=q->next;
            printf("No.%d is out!!\n", q->data);
            free(q);
        }
    
        return (p);
    }
    
    //打印链表
    void Output(LNode* B)
    {
        printf("%d is winner!\n", B->data);
        B = B-> next;
    
    }
    
    //头插法建立链表,长度为n
    void Create(LNode* A)
    {
        LNode *tmp;
    
        int i, n;
    
        printf("输入总人数: ");
        scanf("%d",&n);
        A->data=0;
    
        for(i=n; i!=0; i--)
        {
            LNode *s;
            s = (LNode*)malloc(sizeof(LNode));
            s -> data = i;
            s -> next = A -> next;
            A -> next = s;
            if(i==n)
                tmp=s;
        }
        tmp->next=A->next;
    }
    
    
    int main()
    {
        LNode *A, *B;
        A = (LNode*)malloc(sizeof(LNode));
        A -> next = NULL;
        Create(A);
    
        B=MainPart(A);
        Output(B);
        return 0;
    }

    reply
    0
  • Cancelreply