資料結構Review 線性表練習(約瑟夫問題)

2021-09-24 18:11:34 字數 1245 閱讀 6962

3、約瑟夫問題(10分)

題目內容:

有n只猴子,按順時針方向圍成一圈選大王(編號從1到n),從第1號開始報數,一直數到m,數到m的猴子退出圈外,剩下的猴子再接著從1開始報數。就這樣,直到圈內只剩下乙隻猴子時,這個猴子就是猴王,程式設計求輸入n,m後,輸出最後猴王的編號。

輸入格式:

輸入包含兩個整數,第乙個是n,第二個是m (0 < m,n <=300)。

輸出格式:

輸出包含一行,即最後猴王的編號。

輸入樣例:18 2

輸出樣例:5

時間限制:500ms記憶體限制:32000kb

思路:因涉及節點的刪除操作以及迴圈遍歷資料的操作,我採用迴圈雙鏈表進行資料儲存和處理。

#include #include #include #include using namespace std;

void solution();

//定義雙迴圈鍊錶節點

typedef struct node

node(int n)

} node;

//定義猴子序列的雙迴圈鍊錶類

class monkeylist

if (p == rear)

delete p;

len--;

// cout << num << " has been deleted." << endl;

return true;

}p = p->next;

} while (p != head);

return false;

}public:

monkeylist()

monkeylist(int l)

head = new node(1);

rear = head;

for (int i = 2; i <= len; i++)

}//依次報數,報到m的被刪除

void countoff(int m)

p = p->next;

i++;

}cout << head->number << endl;

}};int main()

system("pause");

return 0;

}void solution()

資料結構Review 線性表練習(字串插入)

1 字串插入 10分 題目內容 有兩個字串str和substr,str和substr的字元個數不超過10 5,只包含大小寫字母和數字。字元個數不包括字串結尾處的 0 將substr插入到str中ascii碼最大的那個字元後面,若有多個最大則只考慮第乙個。輸入格式 輸入資料只有一行,格式為 str s...

002資料結構練習 線性表

1.定義 線性表是n個資料元素的有限序列。資料元素性質相同,物理儲存位置相鄰 loc ai loc a1 i 1 l 2.操作 1 定義線性表 define list init size 100 初始化儲存空間大小 define increment 10 分配儲存空間增量 typedef struc...

資料結構 線性表練習2

題目描述 已知兩個鍊錶a和b分別表示兩個集合,其元素遞增排列。請設計演算法求出a與b的交集,並存放於a鍊錶中。程式 include using namespace std typedef int elemtype typedef struct lnode lnode,linklist lnode為結...