1. 程式人生 > 其它 >演算法練習之約瑟夫問題--(難度2顆星),單向迴圈連結串列解決

演算法練習之約瑟夫問題--(難度2顆星),單向迴圈連結串列解決

技術標籤:演算法

單向迴圈連結串列解決


前言

資料結構與演算法是程式設計師的內功,有時間還是要練習


一、何為約瑟夫問題

約瑟夫問題是個有名的問題:N個人圍成一圈,從第一個開始報數,第M個將被殺掉,最後剩下一個,其餘人都將被殺掉。例如N=6,M=5,被殺掉的順序是:5,4,6,2,3,1。

現在問你最後留下的人是誰?
比如N=6,M=5
留下的就是1
1 2 3 4 5 6 => 6 1 2 3 4 => 6 1 2 3 =>1 2 3 => 1 3 => 1

二、程式碼實現

public class
CircleLink { private Node head; private Node tail; public CircleLink() { this.head = null; this.tail=null; } //構建迴圈連結串列,頭插法 public void insertHead(int data){ Node newNode= new Node(data); if(head==null){ head=newNode; tail=
head; }else{ newNode.next=head; head=newNode; tail.next=head; } } //刪除某個值 public Node delNode(int data){ //從頭部開始遍歷 if(head.value==data){ tail.next=head.next; head.next=null; head=tail.next;
return head;//返回它的下一個值 } Node point1=head; Node point2=head.next; while (point2.value!=data){ point1=point1.next; point2=point2.next; } if(point2==tail){ tail=point1; } point1.next=point2.next; point2.next=null; return point1.next;//返回它的下一個值 } public Node delByYusefu(int nums,Node node){ if(head==tail){ return head; } for (int i = 1; i <=nums-1 ; i++) { node=node.next; } //System.out.println(node.value); return delByYusefu(nums,delNode(node.value)); } public static int lastValue(int n,int m){ CircleLink cl=new CircleLink(); for (int i = n; i >=1 ; i--) { cl.insertHead(i); } Node node=cl.delNode(m); return cl.delByYusefu(m, node).value; } public static void main(String[] args) { int val=lastValue(6,6); System.out.println("最後留下的值:"+val); } } class Node{ public int value; public Node next; public Node(int value) { this.value = value; this.next=null; } }

執行如下:比如刪除5
在這裡插入圖片描述

總結

感覺這次寫的有些麻煩,有時間優化下