- C++
求一个链表题解
- 2024-9-8 15:04:03 @
这一题我本来想用链表做的 但是出错了 最终只好用队列模拟 求大佬给一个链表题解
下方是我的题解(仅供参考)
#include<iostream>
#include<queue>
using namespace std;
queue <int> child;
int cnt = 1;
int main()
{
int a,n;
cin >> a >> n;
for(int i = 1; i <= a; i++){
child.push(i);
}
while(child.empty() == false){
for(int i = 0; i < child.size(); i++){
if(cnt % n == 0){
cout << child.front() << " ";
child.pop();
}
else{
child.push(child.front());
child.pop();
}
cnt++;
}
}
return 0;
}
2 comments
-
xxw6 LV 9 @ 2025-5-22 19:41:35
#include <iostream> using namespace std; // 定义链表节点结构 struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; // 约瑟夫环问题的链表实现 void josephus(int n, int m) { if (n == 1) { cout << 1; return; } // 创建循环链表 ListNode* head = new ListNode(1); ListNode* prev = head; for (int i = 2; i <= n; ++i) { prev->next = new ListNode(i); prev = prev->next; } prev->next = head; ListNode* cur = head; while (cur != cur->next) { for (int i = 1; i < m; ++i) { prev = cur; cur = cur->next; } cout << cur->val << " "; prev->next = cur->next; delete cur; cur = prev->next; } cout << cur->val; } int main() { int n, m; cin >> n >> m; josephus(n, m); return 0; }
-
2024-9-14 21:52:48@
求求了 给个链表题解吧 我现在队列、栈、图、链表中就链表没掌握
- 1