[LeetCode] 876. Middle of the Linked List 链表的中间节点

题目:


思路:

一开始的思路是遍历一遍链表,得到节点的个数num, 再进行遍历,到num/2个节点时便返回(索引从0开始)

不过题解中有一个双指针的解法,特别好,记录下来:

构建两个指针,一个快指针,一个慢指针,快指针每次走两个结点,慢指针每次走一个节点,那么快指针走到nullptr时,慢指针必然在中间节点

代码:

/**
 * 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) {
        // 普通解法
        // int len=0 ;
        // ListNode* cur = head;
        // while(cur){
        //     len++;
        //     cur = cur->next;
        // }
        // int num = len/2;
        // while(num--)    head = head->next;
        // return head;
        // 双指针法
        ListNode* fast=head;
        ListNode* slow=head;
        while(fast!=nullptr && fast->next!=nullptr){
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};

复杂度分析:

时间复杂度:O(N),只需遍历一次单链表

空间复杂度:O(1),只需两个指针的空间

太巧妙了

 

原文地址:https://www.cnblogs.com/ech2o/p/12552596.html