nikunjsoni

876

Mar 16th, 2021
42
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     ListNode* middleNode(ListNode* head) {
  14.         ListNode *slow, *fast;
  15.         slow = fast = head;
  16.         while(!(fast->next == nullptr || fast->next->next == nullptr)){
  17.             slow = slow->next;
  18.             fast = fast->next->next;
  19.         }
  20.         if(fast->next && !fast->next->next) slow = slow->next;
  21.         return slow;
  22.     }
  23. };
RAW Paste Data