题目链接:https://leetcode-cn.com/problems/middle-of-the-linked-list/
题目如下:
思路一:纯思路
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
if(head==NULL) return NULL;
if(head->next==NULL) return head;
int n=0;
ListNode* p=head;
while(p!=NULL){
n++;
p=p->next;
}
p=head;
for(int i=0;i<n/2;i++){
p=p->next;
}
return p;
}
};
思路二:有点小脑筋
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
auto slow=head,fast=head;
while(fast!=NULL&&fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
};