2025-01-12 约瑟夫问题(环形链表)优化
This commit is contained in:
parent
be0ea5b1ea
commit
11bca22901
@ -61,6 +61,38 @@ public class CircleLinkedList {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param k
|
||||||
|
* @param m
|
||||||
|
* 优化改进约瑟夫队列
|
||||||
|
*/
|
||||||
|
private void joseph(int k, int m){
|
||||||
|
JosephNode temp = first;
|
||||||
|
while (true){
|
||||||
|
if (temp.next == first){
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
temp = temp.next;
|
||||||
|
}
|
||||||
|
for(int i = 0; i < k-1; i++){
|
||||||
|
temp = temp.next;
|
||||||
|
first = first.next;
|
||||||
|
}
|
||||||
|
while (true) {
|
||||||
|
if (temp == first){
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
for(int i = 0; i < m-1; i++){
|
||||||
|
temp = temp.next;
|
||||||
|
first = first.next;
|
||||||
|
}
|
||||||
|
System.out.println(first.toString() + "出列");
|
||||||
|
first = first.next;
|
||||||
|
temp.next = first;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
CircleLinkedList circleLinkedList = new CircleLinkedList();
|
CircleLinkedList circleLinkedList = new CircleLinkedList();
|
||||||
Scanner scan = new Scanner(System.in);
|
Scanner scan = new Scanner(System.in);
|
||||||
@ -82,9 +114,11 @@ public class CircleLinkedList {
|
|||||||
circleLinkedList.show();
|
circleLinkedList.show();
|
||||||
}
|
}
|
||||||
if ("j".equals(handle)){
|
if ("j".equals(handle)){
|
||||||
|
System.out.println("请输入开始位置:");
|
||||||
|
int k = scan.nextInt();
|
||||||
System.out.println("请输入出队报数数字:");
|
System.out.println("请输入出队报数数字:");
|
||||||
int m = scan.nextInt();
|
int m = scan.nextInt();
|
||||||
circleLinkedList.joseph(m);
|
circleLinkedList.joseph(k,m);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
scan.close();
|
scan.close();
|
||||||
|
Loading…
Reference in New Issue
Block a user