题目
分析
众所周知,链表无法通过索引访问,那我们试着变成数组可以,也可以用双指针方法。
代码
/**
* 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)
{
vector<ListNode*> A = {head}; //定义链表指针容器
while (A.back()->next != NULL)
A.push_back(A.back()->next); //将指针一个一个放入
return A[A.size() / 2]; //返回中间结点
}
};
class Solution
{
public:
ListNode* middleNode(ListNode* head)
{
ListNode* slow = head; //慢指针
ListNode* fast = head; //快指针
while(fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
}
return slow; //最终得到中间指针
}
};
测试结果
总结
虽然链表不能直接通过索引访问,不过可以呀另想办法,“变成数组”,快慢指针。