https://leetcode.com/problems/middle-of-the-linked-list/

1. Use fast and slow pointer:

  1. //8 ms 6.8 MB
  2. /**
  3. * Definition for singly-linked list.
  4. * struct ListNode {
  5. * int val;
  6. * ListNode *next;
  7. * ListNode() : val(0), next(nullptr) {}
  8. * ListNode(int x) : val(x), next(nullptr) {}
  9. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. ListNode* middleNode(ListNode* head) {
  15. ListNode* runner = head;
  16. ListNode* chaser = head;
  17. while(runner && runner->next){
  18. runner = runner->next->next;
  19. chaser = chaser->next;
  20. }
  21. return chaser;
  22. //1. runner has next next
  23. // runner go
  24. // chaser go
  25. //2. runner has next, has no next next
  26. // return chaser->next;
  27. //3. runner has no next
  28. // return chaser;
  29. }
  30. };

Time Complexity: O(N)
Space Complexity: O(1)