写在前面: 快慢指针走一遍,快指针走完,剩下的慢指针f就是最终返回结果
欢迎关注我的 力扣github仓库,有JavaScript和C++两个版本,每日更新
C++代码:
/**
* 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 *fast=head,*slow=head;
while(fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
};
JS代码:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var middleNode = function(head) {
var fast=head,slow=head;
while(fast && fast.next){
slow=slow.next;
fast=fast.next.next;
}
return slow;
};