
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
if(head==nullptr)
{
return NULL;
}
ListNode *slow=head;
ListNode *fast=head;
while(fast->next!=nullptr&&fast->next->next!=nullptr)
{
slow=slow->next;
fast=fast->next->next;
}
if(fast->next!=nullptr)
{
slow=slow->next;
}
return slow;
}
};

本文介绍了一种在链表中找到中间节点的高效算法。通过使用快慢指针技巧,可以在O(n)时间复杂度内完成任务,而无需额外的空间开销。快指针每次移动两个节点,慢指针每次移动一个节点,当快指针到达链表尾部时,慢指针即指向链表的中点。
903

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



