题目描述:给定一个带有头结点 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。
代码分析: slow=slow->next,fast=fast->next->next;当fast元素遍历完时,slow正好位于中间结点
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode*slow=head,*fast=head;
while(fast&&fast->next){
slow=slow->next,fast=fast->next->next;
}
return slow;
}
};