leetcode 876. Middle of the Linked List
leetcode 876. Middle of the Linked List
不容易出错的写法,慢
class Solution {
public:
ListNode* middleNode(ListNode* head) {
if(!head || !head->next) {
return head;
}
ListNode *single = head, *double_ = head;
int cnt = 0;
while(double_) {
cnt++;
double_ = double_->next;
if((cnt & 1) == 0) {
single = single->next;
}
}
return single;
}
};
这里用cnt计数会拖慢速度,可以考虑优化边界条件判断,取消计数器
1ms写法
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *single = head, *double_ = head;
while(double_ && double_->next) {
double_ = double_->next->next;
single = single->next;
}
return single;
}
};
只要保证double_
和double_->next
都不空,就不会访问到nullptr的成员,就不会出现runtime error