c++猴子选大王 找错

#include<iostream.h>structnode{intnum;node*next;};node*createList(int);voidsearch(nod... #include<iostream.h>
struct node
{
int num;
node *next;
};
node *createList(int);
void search(node *);
void main()
{
int n;
node *listHead=NULL;
cout<<"请输入猴子的个数:"<<endl;
cin>>n;
listHead=createList(n);
search(listHead);
}

node *createList(int n)
{
int i;
node *head;
node *newNode=NULL;
node *tail=NULL;
head=new node;
if(head==NULL)
{
cout<<"内存分配失败!"<<endl;
return NULL;
}
else
{
head->num=1;
head->next=NULL;
tail=head;
}
for(i=2;i<=n;i++)
{
newNode=new node;
if(newNode==NULL)
{
cout<<"内存分配失败!"<<endl;
return NULL;
}
else
{
newNode->num=i;
newNode->next=NULL;
tail->next=newNode;
tail=newNode;
}
}
tail->next=head;
return head;
}

void search(node *head)
{
node *curNode=head;
node *preNode=NULL;
int i=1;
while(curNode->next!=curNode)
{
curNode=curNode->next;
preNode=curNode;
i++;
if(i==3)
{
cout<<"被淘汰的猴子为:"<<curNode->num<<"号。"<<endl;
preNode->next=curNode->next;
curNode=preNode->next;
i=1;
}
}
cout<<"猴王是:"<<preNode->num<<"号。"<<endl;
}
展开
 我来答
日月明自光明3
2011-06-14 · 超过28用户采纳过TA的回答
知道答主
回答量:74
采纳率:0%
帮助的人:83.4万
展开全部
你的意图是建立一个单环链表,然后从链表头开始计数,删除计数为3的节点,重复此过程,直到剩余一个节点。整个过程,建立链表的环节正确,错误在search函数中,其中这两句有问题:
curNode=curNode->next;
preNode=curNode;

此时preNode,不是代表当前节点,而可能是要删除的节点,因为preNode = curNode->next;即下一个节点,正确的代码只需要调正顺序即可,改为:
preNode = curNode;
curNode=curNode->next;
就ok了
memberwin
2011-06-14 · TA获得超过3905个赞
知道大有可为答主
回答量:1000
采纳率:100%
帮助的人:612万
展开全部
以下代码可以正确运行, 错误或者说明在注释中

#include <iostream> //此处不能加.h, iostream是标准库
using namespace std; //要直接使用cout和cin必须要使用名字空间,否则要用std::cin
和std::cout

typedef struct node{ //这儿要使用typedef关键字,以后才能直接用node声明变量,否则
int num; 只能使用 struct node *next这样的方式声明变量
node *next;
}node; //这儿配合 typedef使用,定义node为结构体

node *createList(int);
void search(node *);

void main()
{
int n;
node *listHead = NULL;
cout<<"请输入猴子的个数:"<<endl;
cin>>n;
listHead=createList(n);
search(listHead);
}

node *createList(int n)
{
int i;
node *head;
node *newNode=NULL;
node *tail=NULL;
head=new node;
if(head==NULL)
{
cout<<"内存分配失败!"<<endl;
return NULL;
}
else
{
head->num=1;
head->next=NULL;
tail=head;
}

for(i=2;i<=n;i++)
{
newNode=new node;
if(newNode==NULL)
{
cout<<"内存分配失败!"<<endl;
return NULL;
}
else
{
newNode->num=i;
newNode->next=NULL;
tail->next=newNode;
tail=newNode;
}
}
tail->next=head;
return head;
}

void search(node *head)
{
node *curNode=head;
node *preNode=NULL;
int i=1;
while(curNode->next!=curNode)
{
preNode=curNode; //此处要首先给preNode赋值,否则curNode==
curNode=curNode->next; // preNode了,逻辑上是错的

i++;
if(i==3)
{
cout<<"淘汰的猴子为:"<<curNode->num<<"号。"<<endl;
preNode->next=curNode->next;
delete curNode; //无用的内存记得释放
curNode=preNode->next;
i=1;
}
}
cout<<"猴王是:"<<preNode->num<<"号。"<<endl;
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式