Learn Programming and technology with ease @ developerpublish.com

HomePythonPython Program to Solve Josephus Problem using Linked List

# Python Program to Solve Josephus Problem using Linked List

This Python program solves the Josephus Problem using a circular linked list. The Josephus Problem is a theoretical problem related to a certain counting-out game, where people stand in a circle, and every nth person is eliminated until only one person remains.

The Josephus Problem is a famous theoretical problem related to a certain elimination game. In this problem, a group of people stand in a circle, and at each step, a certain number of people are skipped and the next person is eliminated. This process continues until only one person remains. The challenge is to determine the position of the last remaining person.

## Problem Statement

Given the total number of people in the circle and the number of people to be skipped in each step, write a Python program to find the position of the last remaining person in the circle.

## Python Program to Solve Josephus Problem using Linked List

```class Node:
def __init__(self, data):
self.data = data
self.next = None

def __init__(self):

new_node = Node(data)
else:
temp = temp.next
temp.next = new_node

def remove_node(self, node):
temp = temp.next
else:
prev = None
prev = temp
temp = temp.next
if temp == node:
prev.next = temp.next
break

def josephus(self, step):
while len(self) > 1:
count = 1
while count < step:
temp = temp.next
count += 1
self.remove_node(temp)
temp = temp.next

def __len__(self):
count = 0
while temp:
count += 1
temp = temp.next
break
return count

def get_survivor(self):

def solve_josephus(n, k):
for i in range(1, n + 1):

cll.josephus(k)
return cll.get_survivor()

# Input
total_people = int(input("Enter the total number of people: "))
skip_count = int(input("Enter the number of people to be skipped: "))

# Output
survivor_position = solve_josephus(total_people, skip_count)
print(f"The survivor is at position: {survivor_position}")
```

## How It Works

The program defines a `Node` class and a `CircularLinkedList` class to handle the circular linked list data structure. The `josephus` method simulates the elimination process according to the given step, and the `solve_josephus` function orchestrates the entire process and returns the position of the survivor.

## Input/Output

### You May Also Like

#### Python Program to Remove Duplicates from a Linked List

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...

#### Python Program to Solve the Celebrity Problem

This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...

#### Python Program to Solve n-Queen Problem with Recursion

This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...