【leetcode】876. Middle of the Linked List
Given the head
of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
本题的需求是返回一个链表的中间节点,属于那种一眼就能想到如何解答的easy题目。
解法一,利用map存储每个节点以及节点的位置,然会中间位置的节点。
class Solution {
public:
ListNode* middleNode(ListNode* head) {
// return mid node
// cal the num of the node
unordered_map<int,ListNode*> hash_map;
ListNode* node=head;
int index=0;
while(node!=nullptr){
hash_map[index]=node;
node=node->next;
index++;
}
return hash_map[(index/2)];
}
};
解法二,上述解法空间复杂度太高,其实还可以用快慢指针解决,快指针每个循环走两步,慢指针每个循环走一步,当快指针结束的时候,慢指针刚好走到了一半,即中间位置。(如下图所示 龟兔赛跑)
class Solution {
public:
ListNode* middleNode(ListNode* head) {
// 快慢指针
ListNode* low=head;
ListNode* fast=head;
while(fast && fast->next){
low=low->next;
fast=fast->next->next;
}
return low;
}
};