876. Middle of the Linked List

!!!题目链接!!!

解决方案

/**
 * 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 *le = head;
        ListNode *ri = head;
        int l = 1;
        int r = 1;
        while(ri->next != NULL)
        {
            ri = ri->next;
            r++;
            if(r / 2 >= l)
            {
                le = le->next;
                l++;
            }
        }
        return le;
    }
};

第二种方案:

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        // if(!head->next)
        //     return head;
        ListNode *tmp = head;
        while(head->next && head->next->next){
            head = head->next->next;
            tmp = tmp->next;
        }
        if(head->next)
            tmp = tmp->next;
        return tmp;
    }
};
posted @ 2022-01-07 07:12  ReaIms  阅读(19)  评论(0编辑  收藏  举报