約瑟夫環問題(單迴圈鍊錶實現)

2021-10-08 23:56:04 字數 1273 閱讀 1998

大致思路:

1.利用尾插法建立乙個迴圈鍊錶(建表成功後刪除頭結點)

2.核心演算法:

生成乙個work指標,每走到約定的step-1的位置時停止,利用pdel指標標記後繼結點,迴圈釋放pdel,直到work==work->next停止

#include

#include

#include

using

namespace std;

typedef

int elemtype;

typedef

struct clnodeclnode,

*clinklist;

clinklist initlist

(int n)

;bool

josephus_ring

(clinklist l,

int step)

;bool

showlist

(clinklist l)

;int

main()

clinklist initlist

(int n)

p = head;

if(n !=0)

temp-

>next = head-

>next;

}delete

(head)

;return temp-

>next;

}bool

josephus_ring

(clinklist l,

int step)

clnode *work,

*pdel;

work = l;

while

(work != work-

>next)

cout <<

"\nthe final number is: "

<< work-

>data << endl;

return

true;}

bool

showlist

(clinklist l)

clnode *pshow = l;

while

(pshow-

>next != l)

cout << pshow-

>data;

return

true

;}

showlist函式只是用來顯示生成的鍊錶是否存在結點錯誤以便除錯

約瑟夫環 C語言 單迴圈鍊錶

約瑟夫環 問題描述 編號為1,2,n的n個人圍坐一圈,每人持乙個密碼 正整數 一開始任選乙個正整數作為報數上限值m,從第乙個人開始自1開始順序報數,報到m時停止。報m的人出列,將他的密碼作為新的m值,從他的下乙個人開始重新從1報數,如此下去,直至所有人全部出列為止。試設計乙個程式求出列順序。問題分析...

約瑟夫環問題(不帶頭結點單迴圈鍊錶實現和陣列實現)

q 略 a 為了簡化過程,類中只有3個函式即可,構造,增加,約瑟夫環解決函式 ps 做這道題是為了鞏固鍊錶知識,在這過程中,this指標很隱蔽,code include using namespace std template struct linknode linknode t item,link...

迴圈鍊錶實現約瑟夫環

約瑟夫問題 有n個人圍坐一圈,從第k個人開始數,數到m的那個人出隊。知道最後乙個人出隊。有11個人,從第2個人開始數,數到3的那個人出隊。如下簡圖 這裡有兩個關鍵 1 建立迴圈佇列 不能有頭結點 2 隔m 1步取出該節點 程式如下 include using namespace std typede...