求单链表中间结点

文章目录

题目

力扣链接:https://leetcode-cn.com/problems/middle-of-the-linked-list/description/

image-20211111230522166

思路:

题外数学小题目:

2个人A,B,A速度一个是1m/s.B是2m/s.

那么1s后A走1m,B走2m

​ 2s后A走2m,B走4m

​ 35后A走3m,B走6m。

​ 4s后A走4m,B走8m。

假设(1)一段路长7m,那么4s后,B走到头多1m,A恰好走到路的中间

(2)一段路长8m,那么4s后,B走到头,A走到4m的位置。

因此如果我们将这种规律带到链表中呢?—快慢指针—只要保证是2倍关系就行了—但是最后是1和2,方便。

因为分奇偶结点总数的,B走到NULL结点,或者NULL前面的结点停止。

代码:

struct ListNode* middleNode(struct ListNode* head){
    
    
assert(head!=NULL);
struct ListNode*  fast=head;//快指针
struct ListNode*  slow=head;//慢指针
while(1)
{
    
    
    if(fast==NULL||fast->next==NULL)//这里一定是fast==NULL先考虑,因为当fast=NULL时,fast->next是非法的
    {
    
    
return slow;
    }
   fast=fast->next->next;
   slow=slow->next;
}

}

猜你喜欢

转载自blog.csdn.net/qq_55439426/article/details/121278553