生活随笔
收集整理的這篇文章主要介紹了
(数据结构与算法)单向环形链表解决约瑟夫问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
約瑟夫(Josephu)問題
Josephu問題為: 設編號為1, 2,… n的n個人圍坐一圈,約定編號為k (1<=k<=n) 的人從1開始報數,數到m的那個人出列,它的下一位又從1開始報數,數到m的那個人又出列,依次類推,直到所有人出列為止,由此產生一個出隊編號的序列。
解決思路
用一個不帶頭結點的循環鏈表解決:先構成一個帶有n個節點的單向環形鏈表,然后由k節點起從1開始計數,計到m時,對應節點從鏈表中刪除,然后再從被刪除節點的下一個節點開始數,直到最后一個節點從鏈表中刪除。
代碼實現
單向循環鏈表 和單鏈表區別在于單向循環鏈表的最后一個節點指向第一個節點,且沒有頭結點。
public class CircleSingleLinkedListDemo {public static void main(String
[] args
) {CircleSingleLinkedList list
= new CircleSingleLinkedList();list
.addBoy(10);list
.traverseBoy();list
.countBoy(2,2,10);}
}class CircleSingleLinkedList{public Boy first
= null
;public void addBoy(int num
){if (num
<1){System
.out
.println("num的值不正確");return;}Boy curBoy
= null
;for (int i
= 1; i
<=num
; i
++) {Boy boy
= new Boy(i
);if (i
== 1){first
=boy
;first
.setNext(boy
);curBoy
= first
;}else {curBoy
.setNext(boy
);boy
.setNext(first
);curBoy
= boy
;}}}public void traverseBoy(){if (first
==null
){System
.out
.println("環形鏈表為空");return;}Boy curBoy
= first
;System
.out
.print("遍歷結果:");while (true){System
.out
.print(curBoy
.getNo()+" ");if (curBoy
.getNext()==first
){break;}curBoy
= curBoy
.getNext();}System
.out
.println();}public void countBoy
(int startNo
,int countNum
,int nums
){if (first
==null
|| startNo
<1 ||countNum
>nums
){System
.out
.println("參數輸入有誤");return;}System
.out
.print("出圈順序:");for (int i
= 0; i
<startNo
- 1 ; i
++) {first
= first
.getNext();}Boy helper
=first
;while (true){if (helper
.getNext()==first
){break;}helper
= helper
.getNext();}while (true) {if (first
== helper
){break;}for (int i
= 0; i
< countNum
- 1; i
++) {first
= first
.getNext();helper
= helper
.getNext();}System
.out
.print(first
.getNo()+"-->");first
= first
.getNext();helper
.setNext(first
);}System
.out
.println(first
.getNo());}
}class Boy{private int no
;private Boy next
; public Boy(int no
) {this.no
= no
;}public int getNo() {return no
;}public void setNo(int no
) {this.no
= no
;}public Boy
getNext() {return next
;}public void setNext(Boy next
) {this.next
= next
;}@Overridepublic String
toString() {return "Boy{" +"no=" + no
+'}';}
}
總結
以上是生活随笔為你收集整理的(数据结构与算法)单向环形链表解决约瑟夫问题的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。