for Robot Artificial Inteligence

52. 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* p = head;
        ListNode* q = head;
        int n = 0;
        while(p)
        {
            n++;
            p = p->next;
        }
        n = n/2;
        for(int i =0; i<n; i ++)
        {
            q = q->next;
        }
        return q;

    }
};

Comments