一、 题目
二、思路
这个题的思路呢,就是建立一个环形链表,从1计数,计数到m就删除节点,然后返回最后的节点存的值,有个问题是,循环的结束条件是什么?这是一个难点,下面画图解决!!!
cur->next == cur时,循环结束。
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @param m int整型
* @return int整型
*/
struct ListNode* BuyNode(int x)
{
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
newnode->next = NULL;
newnode->val = x;
return newnode;
}
struct ListNode* CreatList(int n)
{
struct ListNode* phead =BuyNode(1);
struct ListNode* tail = phead;
for(int i = 2;i<n+1;i++)
{
struct ListNode* newnode =BuyNode(i);
//直接尾插
tail->next = newnode;
tail = newnode;
}
tail->next = phead;
return phead;
}
int ysf(int n, int m ) {
// write code here
struct ListNode*plist = CreatList(n);
int count = 1;
struct ListNode* cur = plist;
struct ListNode* prev = NULL;
while(cur->next!=cur)
{
if(count == m)
{
prev->next = cur->next;
free(cur);
cur = prev->next;
count = 1;
}
else {
prev = cur;
cur = cur->next;
count++;
}
}
return cur->val;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @param m int整型
* @return int整型
*/
struct ListNode* BuyNode(int x)
{
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
newnode->next = NULL;
newnode->val = x;
return newnode;
}
struct ListNode* CreatList(int n)
{
struct ListNode* phead =BuyNode(1);
struct ListNode* tail = phead;
for(int i = 2;i<n+1;i++)
{
struct ListNode* newnode =BuyNode(i);
//直接尾插
tail->next = newnode;
tail = newnode;
}
tail->next = phead;
return tail;
}
int ysf(int n, int m ) {
// write code here
struct ListNode*plist = CreatList(n);
int count = 1;
struct ListNode* cur = plist->next;
struct ListNode* prev = plist;
while(cur->next!=cur)
{
if(count == m)
{
prev->next = cur->next;
free(cur);
cur = prev->next;
count = 1;
}
else {
prev = cur;
cur = cur->next;
count++;
}
}
return cur->val;
}
完结!!!