方法1:
class Solution {
public:
ListNode* middleNode(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* cur = head;
int count = 0;
while(cur)
{
count++;
cur = cur->next;
}
for(int i = 0; i < count/2; i++)
{
head = head->next;
}
return head;
}
};
方法2:
class Solution {
public:
ListNode* middleNode(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* slow = head;
ListNode* fast = head->next;
while (fast != NULL){
slow = slow->next;
if (fast->next != NULL){
fast = fast->next->next;
}
else
{
fast = fast->next;
}
}
return slow;
}
};