如何加入中国钟表协会:这个程序是不是语法结构有问题啊?

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/26 07:44:51
我做的一个joseph环程序,一直有问题,语法没有错,但是已运行就要弹出来,于是我就做了一个简单的版本主要是看看我的show函数是不是有问题,但是发现的是问题更奇怪……调试的时候说的是head->next=a1;这一句内存写入冲突,高人看看是不是我的语法结构本来就有问题啊?谢谢…………

源程序如下:
// tryjoseph.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream.h"

struct queen
{
int num;
struct queen *next;
};

void show(struct queen *head,int step)
{
int i,j=1;
struct queen *temp,*temp2=NULL;
temp=head->next;
while(temp->next!=temp)
{
for(i=0;i<step;i++)
{
temp=temp->next;
}
cout<<"第"<<j<<"个出来的是"<<temp->num<<endl;
temp->num=temp->next->num;
temp2=temp->next->next;
delete temp->next;
temp->next=temp2;
j+=1;
}
}

int main(int argc, char* argv[])
{
int step;
struct queen *head=NULL,*a1=NULL,*a2=NULL,*a3=NULL,*a4=NULL;
head->next=a1;
a1->num=1;
a1->next=a2;
a2->num=2;
a2->next=a3;
a3->num=3;
a3->next=a4;
a4->num=4;
a4->next=a1;
cout<<"step?"<<endl;
cin>>step;
show(head,step);

return 0;
}

#include "iostream.h"

struct queen
{
int num;
struct queen *next;
};

void show(struct queen *head,int step)
{
int i,j=1;
struct queen *temp,*temp2=NULL;
temp=head->next;
while(temp->next!=temp)
{
for(i=0;i<step;i++)
{
temp=temp->next;
}
cout<<"第"<<j<<"个出来的是"<<temp->num<<endl;
temp->num=temp->next->num;
temp2=temp->next->next;
delete temp->next;
temp->next=temp2;
j+=1;
}
}

int main(int argc, char* argv[])
{
int step;
//如果想让指针里存数据就应该给它分配空间呀
struct queen *head=NULL,*a1=new queen,*a2=new queen,*a3=new queen,*a4=new queen;

head=a1;//头指针应该这样用,要不就和a1、a2是一样的了
a1->num=1;
a1->next=a2;
a2->num=2;
a2->next=a3;
a3->num=3;
a3->next=a4;
a4->num=4;
a4->next=a1;
cout<<"step?"<<endl;
cin>>step;
show(head,step);

return 0;
}

子函数的功能没注意看,只是帮你把程序调通了,不过你的子函数写的有些繁锁建议看看谭浩强的书。