方法一:首先想到的就是,先求出链表的长度length,再将head往后移动length/2次,上代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int List_Length(ListNode* head)//求出链表的长度
{
int length = 0;
while(head)
{
head = head->next;
length++;
}
return length;
}
ListNode* middleNode(ListNode* head) {
int length = List_Length(head);
int count = length/2 ;
while(count--)//找到中间节点
{
head = head->next;
}
return head;//将结果返回
}
};
方法二:用两个指针 slow 与 fast 一起遍历链表,slow 一次走一步,fast 一次走两步。那么当 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;
ListNode* fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};