数据结构课程设计(C语言),求高手帮忙,帮忙写下面题目的代码,有满意答案一定再加20分

2024-11-20 22:01:15
推荐回答(1个)
回答1:

我是初学者,写的代码不好,仅做参考。很多地方都没有达到要求。没怎么调试,可能会有bug,如果楼主修改不了,在下面回复就好。编了这个也不容易,没有其他更好答案,分就给我吧O(∩_∩)O~

#include
#include
#include

typedef struct Node
{
int iData;
Node *pNext;
}pNode;

void Message(int *M)
{
while(1)
{
printf("Please enter the number of person:/n"); //英文水平有限
scanf("%d", &M[0]);
printf("Please enter the number of who will be killed:/n");
scanf("%d", &M[1]);
if(M[0] < 2 || M[1] < 2)
printf("You entered the wrong number, please enter them again");
else
break;
}
srand((int) time(0));
M[2] = rand() % (M[0] - 1) + 1; //杀手位置随机产生
printf("**********************************************\n");
printf("A total of %d individuals\n",M[0]);
printf("Every %d locations to kill a person\n",M[1]);
printf("The killer is:%d \n", M[2]);
printf("**********************************************\n");
}
pNode *CreatChain(int *M)
{
int i = 0;
pNode *pHead,*pre, *cur;

pHead = (Node*)malloc(sizeof(Node));
if(M[2] != 1)
pHead->iData = 1;
else
pHead->iData = -1; //杀手的位置置-1
cur = pHead;
for (i = 2; i < M[0] + 1; i++) //创建循环链表
{
pre = (Node*)malloc(sizeof(Node));
if (i == M[2])
pre->iData = -1;
else
pre->iData = i;
pre->pNext = NULL;
cur->pNext = pre;
cur = pre;
}
cur->pNext = pHead;
return pHead;
}

void KillBegin(pNode *pHead, int *M)
{
int iNum = M[0]; //记录剩余人数
int iCount = 1; //每M个被杀
int i = 1;
pNode *pre, *cur;
pre = pHead;
cur = pHead->pNext;
while (iNum > 2)
{
iCount++; //因M>2,第一轮从2号开始判断(M = 1杀起来没意义)
if(iCount == M[1])
{
if(cur->iData == -1) //判断第M个是否是杀手
{
pre = pre->pNext;
cur = cur->pNext;
}
pre->pNext = cur->pNext;
cur->pNext = NULL;
printf("The %dth victim will be:%d \n", i, cur->iData);
i++;
free(cur); //杀掉第M个人
cur = pre->pNext;
iCount = 0;
iNum--;
}
else
{
pre = pre->pNext;
cur = cur->pNext;
}
}
printf("**********************************************\n");
if(pre->iData != -1)
printf("The hero is: %d\n", pre->iData); //输出英雄位置
else
printf("The hero is: %d\n", cur->iData);
free(pre);
free(cur);
}

int main()
{
int M[3] = ; //M[0]总人数,M[1]杀第几个人,M[2]杀手位置
pNode *pHead = NULL;
Message(M); //获得M信息
pHead = CreatChain(M); //创建信息循环链表

KillBegin(pHead, M); //开始杀人
return 0;
}