我改写了一些20讲“魔术师发牌问题”的内容,但运行错误,帮忙看看
本帖最后由 圣狄雅哥 于 2018-1-14 15:34 编辑#include <stdio.h>
#include <stdlib.h>
#defineCardNumber 13
typedef struct node
{
int data;
struct node *next;
}sqlist, *linklist;
linklist CreateLinkListtail()
{
linklist head = NULL;
linklist s, r;
int i;
r = head;
for(i=1; i <= CardNumber; i++)
{
s = (linklist)malloc(sizeof(sqlist));
s->data = 0;
if(head == NULL)
head = s;
else
r->next = s;
r = s;
}
r->next = head;
return head;
}
linklist CreateLinkListhead()
{
linklist s,*L,tail=NULL;
int i;
L=(linklist*)malloc(sizeof(sqlist));
(*L)->next=NULL;
for(i=1; i <= CardNumber; i++)
{
s = (linklist)malloc(sizeof(sqlist));
s->data = 0;
if(tail == NULL)
tail= s;
else
{
s->next=(*L)->next;
(*L)->next=s;
}
}
tail->next=s;
return s;
}
// 发牌顺序计算
void Magician(linklist head)
{
linklist p;
int j;
int Countnumber = 2;
p = head;
p->data = 1;//第一张牌放1
while(1)
{
for(j=0; j < Countnumber; j++)
{
p = p->next;
if(p->data != 0)//该位置有牌的话,则下一个位置
{
j--;
}
}
if(p->data == 0)
{
p->data = Countnumber;
Countnumber ++;
if(Countnumber == 14)
break;
}
}
}
// 销毁工作
void DestoryList(linklist head)
{
linklist p;
if(head==NULL)
return 0;
while(head)
{
p=head->next;
free(head);
head=p;
}
return 1;
}
int main()
{
linklist p;
int i;
char opp;
while(1)
{
printf("输入1.尾插法建立循环链表,2.头插法建立循环链表。\n");
scanf("%c",&opp);
if(opp=='1')
{
p = CreateLinkListhead();
break;
}
else
{
p = CreateLinkListtail();
break;
}
}
Magician(p);
printf("按如下顺序排列:\n");
for (i=0; i < CardNumber; i++)
{
printf("黑桃%d ", p->data);
p = p->next;
}
DestoryList(p);
return 0;
}
验证后发现程序的错误只在于头插法建立循环链表,其他无误
页:
[1]