以前练过的题,emm,还是不太熟
题目
leetcode
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.Notice that you should not modify the linked list.

函数
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head) {
}
分析

实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *fast,*slow;
fast = head;
slow = head;
while (fast && fast->next){
fast = fast->next->next;
slow = slow->next;
if (fast == slow){
fast = head;
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
return slow;
}
}
return NULL;
}

这篇博客介绍了如何使用快慢指针的方法解决LeetCode中的链表环节点检测问题。通过定义两个指针,一个每次移动两步,另一个每次移动一步,当它们相遇时,慢指针所在位置即为链表环的起点。如果没有环,则返回空。
387

被折叠的 条评论
为什么被折叠?



