回 帖 发 新 帖 刷新版面

主题:利用c语言结构体编写数3游戏,提示程序出错,求解,谢谢

利用c语言的结构体编写数三游戏,编号1-10,报数1、2、3,当报到3的人退出,问最后剩下的一人的编号是什么?  
我写的这段代码没有编译错误,但是一运行就提示程序错误,请问各位高手究竟问题在哪里呢?万分感谢啊!以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define n 10
#define New (struct node *)malloc(sizeof (struct node))
struct node
{
    int number;
    struct node *next;
};
struct node *build()
{
    int i;
    struct node *p,*q,*head;
    head=NULL;
    i=0;
    while (i<10)
    {
        i=i+1;
        p=New;
        p->number=i;
        if (head==NULL)
            head=p;
        else
            q->next=p;
        q=p;
        if (i==10)
            q->next=head;
    }
    return head;
}
struct node *work(struct node *head)
{
    int k;
    struct node *p,*q;
    p=head;
    k=0;
    while ()
    {
        q=p;
        k=k+1;
        p=q->next;
        if (k==2)
        {
            k=0;
            q->next=p->next;
            free(p);
            p=q->next;
        }
    }
    return p;

}
void main()
{
    struct node *head,*p;
    head=build();
    printf("%d is head\n",*head);
    p=work(head);
    printf("%d is left\n",p->number);
}
谢谢

回复列表 (共3个回复)

沙发

你那个 #define New (struct node*)malloc(sizeof(struct node))应该放在
[code=c]
struct&#160;node
{
&#160;&#160;&#160;&#160;int&#160;number;
&#160;&#160;&#160;&#160;struct&#160;node&#160;*next;
};
[/code]
后面,就没有问题了(去掉&#160;)

板凳

struct&#160;node
{
&#160;&#160;&#160;&#160;int&#160;number;
&#160;&#160;&#160;&#160;struct&#160;node&#160;*next;
};

&#160?? 是什么意思?看不明白

3 楼

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define n 10
#define New 
struct node
{
    int number;
    struct node *next;
};
struct node *build()
{
    int i;
    struct node *p,*q,*head;
   
head=p=(struct node *)malloc(sizeof (struct node));
head->next=head;
head->number=1;
    for(i=2;i<=n;i++)
    {   q=(struct node *)malloc(sizeof (struct node));
        q->number=i;
         p->next=q;
         q->next=head;
         p=q;
            
    }
    return head;
}
void pri(struct node *head)
{struct node *p;
      p=head;
      printf("建立的环:");
    for(int i=0;i<n;i++)
    {
       printf("%d ",p->number);
       p=p->next;
    };
    printf("\n");
}
struct node *work(struct node *head)
{
    int k=1;
    struct node *p,*q;
    p=head;
    k=1;
    while(p->next!=p)
    {
       if(k==2)
        {  q=p->next;
        p->next=q->next;
        p=p->next;
        k=1;
    
        free(q);
    }
       else{
           p=p->next;
            k++;
       }
        }
      
    
    return p;

}
void main()
{
    struct node *head,*p;
    head=build();
    pri(head);
    printf("%d is head\n",*head);
   p=work(head);
  printf("%d is left\n",p->number);
}

我来回复

您尚未登录,请登录后再回复。点此登录或注册