题解 | #环形链表的约瑟夫问题#
环形链表的约瑟夫问题
https://www.nowcoder.com/practice/41c399fdb6004b31a6cbb047c641ed8a
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @param m int整型
* @return int整型
*/
#include<stdlib.h>
typedef struct LSnode
{
int data;
struct LSnode* next;
}LSnode;
LSnode* LSnode_space(int n)
{
LSnode* p1 = (LSnode*) malloc(sizeof(LSnode));
p1->data = n;
p1->next = NULL;
return p1;
}
LSnode* LSnode_creat(int n)
{
//创建扫兵卫
LSnode* phead = LSnode_space(-1);
LSnode* tmp = phead;//储存链头
int i = 1;
while(i <= n)
{
LSnode* newnode = LSnode_space(i);
phead->next = newnode;
phead = newnode;
i++;
}
LSnode* ed = phead->next = tmp->next;//首位相连
free(tmp);
phead = tmp = NULL;
return ed;
}
int ysf(int n, int m ) {
// write code here
//创建闭环
LSnode* phead = LSnode_creat(n);
//计算
while(phead != phead->next)//只有一个
{
int count = 1;
LSnode* prev = NULL;//储存上一个节点
while(count < m)
{
prev = phead;
phead = phead->next;
count++;
}
//删除
LSnode* del = phead;
prev->next = phead->next;
phead = phead->next;//从下一个开始
free(del);
del = NULL;
}
return phead->data;
}
//yeyeyeyeye
查看13道真题和解析