题目:
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.
Example 1:
Input: [1,2,3,4,5] Output: Node 3 from this list (Serialization: [3,4,5]) The returned node has value 3. (The judge's serialization of this node is [3,4,5]). Note that we returned a ListNode object ans, such that: ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6] Output: Node 4 from this list (Serialization: [4,5,6]) Since the list has two middle nodes with values 3 and 4, we return the second one.
Note:
- The number of nodes in the given list will be between
1
and100
.
思路:
题目很简单,找出链表中点,解法也很多样。一种是two pass,先遍历一遍数出node个数,然后再遍历一次走二分之一的node个数即可。因为总node数也就100个,用vector来记录链表中的node,返回二分之一Index部分即可。这里介绍one pass双指针解法,同时从头开始,一个指针每次走两步,一个走一步,当快指针走到空时,满指针即为中点。
代码:
/**
* 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) {
ListNode* p=head;
ListNode* q=head;
while(q&&q->next)
{
p=p->next;
q=q->next;
q=q->next;
}
return p;
}
};