寫出一個雙向的循環(huán)鏈表,弄一個計(jì)數(shù)器,我定義的是到三的時候,自動刪除當(dāng)前節(jié)點(diǎn),很簡單。
package Com;import java.util.Scanner;/* * 約瑟夫環(huán)問題,有n個人組成的圈,數(shù)到3的那個人出列,下個人繼續(xù)從一開始 */public class Josephus { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = Integer.parseInt(s.nextLine()); Node first = new Josephus().startRun(n ); int count = 1; while(first.next != first) { first = first.next; count++; if(count == 3) { first.PRevious.next = first.next; first.next.previous = first.previous; first = first.next; count = 1; } } System.out.println("最后剩下來的數(shù)字為:"+first.n); } public Node startRun(int n) { Node first = new Node(); first.previous = null; first.n = n ; //這里給鏈表賦值,倒敘 Node current = first; Node last = first; while((--n)>0) { current.next = new Node(); current = current.next; current.n = n; current.previous = last; last = current; } current.next = first; first.previous = current; return first; } class Node { int n ; Node next; Node previous; }}
新聞熱點(diǎn)
疑難解答
圖片精選