forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
46 lines (34 loc) · 833 Bytes
/
main2.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
43
44
45
46
/// Source : https://leetcode.com/problems/middle-of-the-linked-list/description/
/// Author : liuyubobobo
/// Time : 2018-07-28
#include <iostream>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Two Linear Scans
/// Calculate length and get the answer
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
ListNode* middleNode(ListNode* head) {
int len = 0;
ListNode* cur = head;
while(cur != NULL)
len ++, cur = cur->next;
if(len == 1)
return head;
int k = len / 2;
cur = head;
for(int i = 0 ; i < k ; i ++)
cur = cur->next;
return cur;
}
};
int main() {
return 0;
}