大家好,我是苏貝,本篇博客带大家刷题,如果你觉得我写的还不错的话,可以给我一个赞👍吗,感谢❤️
点击查看题目
首先我们要明确一点,题目要求我们要用环形链表,所以用数组等是不被允许的。
思路:
下面以总共有5个人,编号为1、2、3、4、5,从编号为1的人开始报数,报到2时离开为例:
1.创建环形链表
BuyListNode函数是创建单个节点,CreateListNode函数是创建环形链表,它的返回值是我们创建的第一个节点
typedef struct ListNode11
{int val;struct ListNode11* next;
}ListNode;ListNode* BuyListNode(int x)
{ListNode* newnode=(ListNode*)malloc(sizeof(ListNode));if(newnode==NULL){perror("malloc fail");return NULL;}newnode->val=x;newnode->next=NULL;return newnode;
}ListNode* CreateListNode(int n)
{int i=1;ListNode* phead,* ptail;phead=ptail=BuyListNode(i++);while(i<=n){ptail->next=BuyListNode(i++);ptail=ptail->next;}ptail->next=phead;return phead;
}
2.报数
上面的思路中,如果有人报到2,让前一个结点指向该节点的后一个节点,再释放该节点,这该如何实现呢?
很简单,让cur先走,prev指向cur的前一个结点,如果报到2,让prev指向cur的下一个节点,再free(cur)即可。
注意:当报到2时不仅要free(cur),还要将控制报数的变量 i 置为1
int ysf(int n, int m ) {ListNode* head=CreateListNode(n);ListNode* cur=head;ListNode* prev=NULL;int i=1;while(cur->next!=cur){if(i==m){prev->next=cur->next;free(cur);cur=prev->next;i=1;}else {prev=cur;cur=cur->next;i++;}}return cur->val;
}
完整代码:
typedef struct ListNode11
{int val;struct ListNode11* next;
}ListNode;ListNode* BuyListNode(int x)
{ListNode* newnode=(ListNode*)malloc(sizeof(ListNode));if(newnode==NULL){perror("malloc fail");return NULL;}newnode->val=x;newnode->next=NULL;return newnode;
}ListNode* CreateListNode(int n)
{int i=1;ListNode* phead,* ptail;phead=ptail=BuyListNode(i++);while(i<=n){ptail->next=BuyListNode(i++);ptail=ptail->next;}ptail->next=phead;return phead;
}int ysf(int n, int m ) {ListNode* head=CreateListNode(n);ListNode* cur=head;ListNode* prev=NULL;int i=1;while(cur->next!=cur){if(i==m){prev->next=cur->next;free(cur);cur=prev->next;i=1;}else {prev=cur;cur=cur->next;i++;}}return cur->val;
}
好了,那么本篇博客就到此结束了,如果你觉得本篇博客对你有些帮助,可以给个大大的赞👍吗,感谢看到这里,我们下篇博客见❤️