java实现双链表求解约瑟夫环问题,并输出出环顺序
时间: 2023-06-18 07:02:58 浏览: 104
下面是Java实现双链表求解约瑟夫环问题的代码,其中包括了输出环顺序的部分:
```
import java.util.Scanner;
public class Josephus {
private Node head;
private Node tail;
private int size;
private class Node {
private int data;
private Node prev;
private Node next;
public Node(int data) {
this.data = data;
}
}
public Josephus() {
head = null;
tail = null;
size = 0;
}
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = head;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
size++;
}
public void remove(Node node) {
if (node == head) {
head = node.next;
} else if (node == tail) {
tail = node.prev;
} else {
node.prev.next = node.next;
node.next.prev = node.prev;
}
size--;
}
public void solve(int m) {
Node p = head;
while (size > 1) {
for (int i = 0; i < m - 1; i++) {
p = p.next;
}
Node temp = p.next;
remove(p);
p = temp;
}
System.out.println("The order of the Josephus circle is:");
System.out.print(head.data + " ");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the number of people:");
int n = scanner.nextInt();
System.out.println("Please enter the value of m:");
int m = scanner.nextInt();
Josephus josephus = new Josephus();
for (int i = 1; i <= n; i++) {
josephus.add(i);
}
josephus.solve(m);
scanner.close();
}
}
```
在这个程序中,我们首先定义了一个双链表类`Josephus`,其中包括了`Node`节点类和相应的链表操作,比如`add`、`remove`等。
在`solve`方法中,我们使用一个指针`p`来遍历链表,每次移动`m-1`个位置,然后将`p`指向的节点删除。直到链表中只剩下一个节点,输出该节点的值。
最后,在`main`方法中,我们输入人数`n`和`m`,然后创建一个`Josephus`对象,并将人数添加到双链表中。最后调用`solve`方法求解约瑟夫环问题,并输出环顺序。
阅读全文