这是小罗第一次在LeetCode上写的链表题呀!
先遍历一遍链表,然后得到链表的长度,返回中间结点
/**
* 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) {
ListNode* p=head;
ListNode* q=head;
int k=0;
while(p){
p = p->next;
k++;
}
int mid = k/2;
int t = 0;
while(t!=mid){
q = q->next;
t++;
}
return q;
}
};