leetcode876. 链表的中间结点

876. 链表的中间结点

方法一:

最简单的做法,先求出整个链表的长度,再求1/2处节点的位置。

复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        if(head == nullptr) return nullptr;
        int cnt = 0;
        ListNode *cur = head;
        while(cur!=nullptr){
            ++ cnt;
            cur = cur->next;
        }

        cnt = cnt / 2;
        cout << cnt << endl;
        while(cnt --){
            head = head->next;
        }
        return head;
    }
};
复制代码

时间很快,空间击败了7%

在C++中,++cnt比cnt++要快一些。

方法二:

经典双指针,快指针比满指针快一倍。但是比较坑的地方在于,在双数的时候,要特别注意边界问题。

复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        ListNode *f = head;
        ListNode *s = head;

        while(f ->next != nullptr && f->next->next != nullptr){
            f = f->next->next;
            s = s->next;
        }
        
        if(f->next != nullptr){
            s = s->next;
        }
        return s;
    }
}; 
复制代码
posted @   luxiayuai  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示