首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

请大家帮忙看一看这个小程序错在哪?解决方案

2012-02-22 
请大家帮忙看一看这个小程序错在哪?#includeStdio.h #includeConio.h #includestdlib.htypedefstruc

请大家帮忙看一看这个小程序错在哪?
#include   "Stdio.h "
#include   "Conio.h "
#include   <stdlib.h>
typedef   struct   node{
    int   code;
    struct   node   *next;
}NODE,*LinkList;
LinkList   creat_list(int   n)
{
    LinkList   head,p;
    int   i;
    head=(NODE*)malloc(sizeof(NODE));
    if(!head)
    {
        printf( "memory   allocation   error!\n ");
        return   NULL;
    }
    for(i=n;i> 1;--i)
    {
        p=(NODE   *)malloc(sizeof(NODE));
        if(!p)
        {
            printf( "memory   allocation   error!\n ");
        }
        p-> code=i;
        p-> next=head-> next;
        head-> next=p;
    }
    return   head;
}
void   output(LinkList   head)
{
    LinkList   p;
    p=head;
    do
    {
        printf( "%4d ",p-> code);
        p=p-> next;
    }while(p!=head);
    printf( "\n ");
}
void   play(LinkList   head,int   n)
{
    LinkList   p,q;
    int   c=0,k;
    p=head;
    c=1;
    k=n;
    while(k> 1)
    {
        if(c==2)
        {
            q=p-> next;
            p-> next=q-> next;
            printf( "%4d ",q-> code);
            free(q);
            c=0;
            k--;
        }
        else{p=p-> next;c++;}
    }
}
int   main(void)
{
    LinkList   head;
    int   n;
    printf( "input   the   number   of   players: ");
    scanf( "%d ",&n);
    head=creat_list(n);
    if(head)
    {
        output(head);
        play(head,n);
    }
  /*   此处添加你自己的代码   */
}
选首领,N个游戏者围成一圈,从第一个人开始顺序报数1.2.3.凡报到3   者退出圈子,最后留在圈中的人即为首领.
望大家多多指导,谢谢

[解决办法]
too long,极为无语,给你一个简单点的代码吧
==============================================================
#include <iostream>
using namespace std;
int main()
{int i,k,m,n,num[50],*p;
cout < < "input number of person: n= ";
cin> > n;
p=num;
for (i=0;i <n;i++)
*(p+i)=i+1; // 以1至n为序给每个人编号
i=0; // i为每次循环时计数变量
k=0; // k为按1,2,3报数时的计数变量
m=0; // m为退出人数
while (m <n-1) // 当退出人数比n-1少时(即未退出人数大于1时)执行循环体


{if (*(p+i)!=0) k++;
if (k==3) // 将退出的人的编号置为0
{*(p+i)=0;
k=0;
m++;
}
i++;
if (i==n) i=0; // 报数到尾后,i恢复为0
}
while(*p==0) p++;
cout < < "The last one is NO. " < <*p < <endl;
return 0;
}
[解决办法]
写这么长确实没什么意义,在这里给你指出几个需要注意的错误:
在creat_list这个函数里,看你的意图应该是建立一个循环链表,但是你的代码是实现不了这个功能的,给你修改一下
LinkList creat_list(int n)
{
LinkList head,p;
int i;
head=(NODE*)malloc(sizeof(NODE));
if(!head)
{
printf( "memory allocation error!\n ");
return NULL;
}
head-> next = head;//建立链表的时候就要让这个链表变成一个循环链表,虽然他只有一个结点
head-> code = 1; //既然你把head作为链表的第一个结点,那么应该给code赋值
for(i=n;i> 1;--i)
{
p=(NODE *)malloc(sizeof(NODE));
if(!p)
{
printf( "memory allocation error!\n ");
return NULL;//中间出错的时候应该马上返回,并应该释放所有malloc分配的资源,释放资源的代码你自己实现吧。
}
p-> code=i;
p-> next=head-> next;
head-> next=p;
}
return head;
}

热点排行