forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main3.cpp
42 lines (31 loc) · 774 Bytes
/
main3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/// Source : https://leetcode.com/problems/middle-of-the-linked-list/description/
/// Author : liuyubobobo
/// Time : 2018-08-02
#include <iostream>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Fast and Slow Pointers
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
ListNode* middleNode(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};
int main() {
return 0;
}