力扣-876题 链表的中间节点(C++)

力扣-876题 链表的中间节点(C++),第1张

力扣-876题 链表的中间节点(C++)

题目链接:https://leetcode-cn.com/problems/middle-of-the-linked-list/
题目如下:

思路一:纯思路

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        if(head==NULL) return NULL;
        if(head->next==NULL) return head;

        int n=0;
        ListNode* p=head;
        while(p!=NULL){
            n++;
            p=p->next;
        }

        p=head;
        for(int i=0;inext;
        }

        return p;

    }
};

思路二:有点小脑筋

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        auto slow=head,fast=head;

        while(fast!=NULL&&fast->next!=NULL){
            slow=slow->next;
            fast=fast->next->next;
        }

        return slow;
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5699090.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存