Title Description
Given a non-empty list with a single head of the first node, an intermediate node returns the list.
If there are two intermediate nodes, the second intermediate node is returned.
Example 1:
Input: [1,2,3,4,5]
Output: this list node 3 (SEQ form: [3,4,5])
Returns the value of node 3. (This evaluation system is expression of the sequence node [3,4,5]).
Note that, we return an object of type ListNode ANS, so 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: this list node 4 (SEQ form: [4,5,6])
Since the list has two intermediate nodes, the value of 3 and 4, respectively, we return to the second node.
Solution one: set list of variables (C ++)
/**
* 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) {
vector<ListNode*> A = {head};
while (A.back()->next != NULL)
A.push_back(A.back()->next);
return A[A.size()/2];
}
};
Solution two: the speed of the pointer (C ++)
- Two pointers point to the initial head pointer.
- If the pointer is null fast or faster next pointer is null, then the time is the answer to slow pointer, move over.
- Each round to move fast pointer to be moved twice, once slow need to move the pointer. Step two jumps.
C ++ graphical pointer speed proved last goose-site interviews also met :)
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *p = head, *q = head;
while(q!=nullptr && q->next!=nullptr)
{
p = p->next;
q = q->next->next;
}
return p;
}
};