leetcode twopointer 876 The middle node of the linked list

THE

problem

Insert picture description here

achieve

Code

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };

快慢指针问题, 让快指针走两步,慢指针走一步。 区间确定好之后, 再去调整单双问题, 单双问题不是现在考虑的。
其实还可以先统计ssize大小,然后折半遍历,这个复杂度高一点,但是也为n。




*/
class Solution {
    
    
public:
   ListNode* middleNode(ListNode* head) {
    
    
       ListNode* fast = head;
       ListNode* slow = head;
       while(fast!=nullptr && fast->next!=nullptr){
    
    
           fast = fast->next->next;
           slow = slow->next;
       }
       return slow;

   }
};

Summary and reflection

  1. Pay attention to consideration of boundary issues.

Guess you like

Origin blog.csdn.net/liupeng19970119/article/details/114048887