zoukankan      html  css  js  c++  java
  • [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),只需两个指针的空间

    太巧妙了

     

  • 相关阅读:
    Java 运动模糊
    Efounds笔试
    Algorithms code
    Java 画图
    Java 笔记
    Java 对二值化图片识别连通域
    工厂模式
    数据库克隆
    SQL优化
    微信调起jssdk一闪而过
  • 原文地址:https://www.cnblogs.com/ech2o/p/12552596.html
Copyright © 2011-2022 走看看