题目给出一个有头节点的非空单链表,要求返回链表的中间节点。
如果链表节点数为偶数时,返回第二个中间节点,代码如下:
/**
* 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; //快指针
ListNode* slow = head; //慢指针
while(fast!=NULL &&fast->next != NULL)
{
fast = fast -> next ->next;
slow = slow-> next;
}
return slow;
}
};
在while条件判断语句中,如果使用 while(fast&&fast != nullptr)就会报错,Line 16: Char 36: runtime error: member access within null pointer of type 'ListNode' (solution.cpp).
在写快慢指针条件判断时,推荐写以下两种写法:
while(fast&&fast->next)
while(fast != NULL && fast->next != NULL)