1,题目要求
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
找到一个单链表的中间节点。
2,题目思路
对于这道题,个人的想法是利用一个vector,对单链表中的节点进行记录,最后直接返回vector中间的元素即可。
3,程序源码
static int pr = []() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
ListNode* middleNode(ListNode* head) {
vector<ListNode*> val;
ListNode* node = head;
while(node!= nullptr)
{
val.push_back(node);
node = node->next;
}
int l = val.size();
return val[l/2];
}
};