常规思路是先统计链表的节点个数,然后将头结点定位到中间结点的位置上然后返回头结点。
/**
* 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) {
int count = 0;
ListNode *countList = head;
while(countList!=NULL)
{
count++;
countList = countList->next;
}
int stopNode = count/2;
if(count%2==1)
{
for(int i = 0;i<stopNode;i++)
{
head = head ->next;
}
}
else if(count%2==0)
{
for(int i = 0;i<stopNode;i++)
{
head = head ->next;
}
}
return head;
}
};
也可以采用双指针中的快慢指针思想:快指针走的速度是慢指针的两倍,当快指针走到队尾时慢指针指的位置就是中间结点的位置上
/**
* 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 *fastList = head;
ListNode *slowList = head;
while(fastList!=NULL&&fastList->next!=NULL)
{
slowList = slowList->next;
fastList = fastList->next->next;
}
return slowList;
}
};