2.6 Given a circular linked list, implement an algorithem which returns the node at the beginning of the loop.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};ListNode* findBeginning(ListNode *head) {
ListNode *fast = head;
ListNode *slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
break;
}
}
if (fast == NULL || fast->next == NULL) {
return NULL;
}
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return fast;
}
本文介绍了一种算法,用于找到给定环形链表中循环开始的节点。通过使用快慢指针的方法,可以在O(n)的时间复杂度内找到循环的起始节点。
99

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



