所以我正在创建一个循环链表来解决约瑟夫斯问题的任务。我的C ++课程教授非常糟糕,我真的不知道如何用C ++做任何事情。我正在尝试编写一个迭代器来横向列表,但我不知道从哪里开始或如何实现它。谁能给我一个关于如何开始编码的建议或建议?
答案 0 :(得分:0)
约瑟夫斯问题是如果N个人决定通过安排选举一位领导人 将自己排成一个圈,并消除圈中的每个Mth人,每个人退出时的排名都会接近。查找哪个人将是最后一个剩下的人。 这是在C ++中此问题的非常简单的实现。
#include<iostream>
#include<stdio.h>
#include<cstdlib>
#include<stdlib.h>
using namespace std;
struct node
{ int info;
struct node *next;
}arr[]={{rand(),arr+1},{rand(),arr+2},{rand(),arr+3},{rand(),arr+4},{30,arr}};
typedef struct node* Node;
void josephus(Node);
int main()
{
josephus(arr);
system("pause");
}
void josephus(Node head)
{
Node ptr,temp;
int length=1,position,i;
ptr=head;
while(ptr->next!=head)
{
ptr=ptr->next;
length++;
}
ptr=head;
printf(" Enter the position at which element should get eliminated ");
scanf("%d",&position);
while(length>1)
{
i=1;
while(i<position)
{
ptr=ptr->next;
i++;
}
temp=ptr;
ptr=ptr->next;
free(temp);
length--;
}
printf("\n Last Element Left is %d Its address is %u \n",ptr->info,ptr);
}
有关更多详细信息,请访问- https://github.com/SahdevKansal02/Data-Structures-And-Algorithms.git