数据结构:单向环形链表
生活随笔
收集整理的這篇文章主要介紹了
数据结构:单向环形链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?約瑟夫問題
public class Josephus {public static void main(String[] args){SingleCircleLinkedList single = new SingleCircleLinkedList();single.addBoyNode(5);single.showNodes();single.countNode(1, 2, 5);} }class SingleCircleLinkedList{// 創建first節點private BoyNode first = null;public void addBoyNode(int nums){if(nums < 1){System.out.println("nums的值不正確");return;}BoyNode temp = null; // 輔助節點for(int i=1;i<=nums;i++){BoyNode bn = new BoyNode(i);if(i == 1){first = bn;first.setNext(first);temp = first;}else{temp.setNext(bn);bn.setNext(first);temp = bn;}}}// 遍歷當前環形鏈表public void showNodes(){if(null == first){return;}BoyNode temp = first;do{System.out.println(temp.getNo());temp = temp.getNext();}while(first != temp);}/*** startNo:從哪個位置開始數* countNum 數幾次* nums:一共幾個人 */public void countNode(int startNo, int countNum, int nums){if(null == first || startNo<1 || startNo>nums){System.out.println("參數輸入有誤,請重新輸入");return;}BoyNode helper = first;//輔助節點while(true){if(helper.getNext() == first){break;}helper = helper.getNext();}for(int j=0; j<startNo-1;j++){first = first.getNext();helper = helper.getNext();}// 同時移動first,helper m-1次while(true){// 圈中只有一個人if(first == helper){break;}for(int j=0;j<countNum-1;j++){first = first.getNext();helper = helper.getNext();}System.out.printf("小孩%d出圈!",first.getNo());// 讓first指向的小孩節點出圈first = first.getNext();helper.setNext(first);}System.out.printf("最后的小孩%d出圈!",first.getNo());} }class BoyNode{private int no;private BoyNode next;public int getNo() {return no;}public void setNo(int no) {this.no = no;}public BoyNode getNext() {return next;}public void setNext(BoyNode next) {this.next = next;}public BoyNode(int no){this.no = no;} }?
總結
以上是生活随笔為你收集整理的数据结构:单向环形链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java:final,finally,f
- 下一篇: java:static关键字