其他分享
首页 > 其他分享> > 876. Middle of the Linked List

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;
    }
};

标签:tmp,head,le,ListNode,876,List,next,Middle,int
来源: https://www.cnblogs.com/Pomelos/p/15773590.html