タイトル説明
最初のノードの単一ヘッドを有する非空リストが与えられると、中間ノードのリストが返されます。
二つの中間ノードがある場合、第二の中間ノードが返されます。
思考
- 最初の統計リストのサイズに押し込まスタックを使用し、その後、中間位置にポップアップ表示
- サイズに統計情報の配列を使用して、中間の位置に戻します
- 指の速度、低速と高速の2つのポインタと一緒にリストを横断。遅い時間は2倍の速移動、さらに一歩進んでください。そして、リストは途中で遅い必ずしも、速いの終わりに到達したとき。
コード
この方法の一つ:
class Solution {
public:
ListNode* middleNode(ListNode* head) {
int count = 0;
if(head==NULL)
return NULL;
stack<ListNode*> s;
ListNode* cur = head;
while(cur!=NULL)
{
s.push(cur);
count++;
cur = cur->next;
}
int nb = count;
while(nb>count/2+1)
{
s.pop();
nb--;
}
return s.top();
}
};
方法2:
class Solution {
public:
ListNode* middleNode(ListNode* head) {
int count = 0;
if(head==NULL)
return NULL;
vector<ListNode*> s;
ListNode* cur = head;
while(cur!=NULL)
{
s.push_back(cur);
count++;
cur = cur->next;
}
return s[count/2];
}
};
方法3:
class Solution {
public:
ListNode* middleNode(ListNode* head) {
if(head==NULL)
return NULL;
ListNode* fast = head;
ListNode* slow = head;
int a = 0;
while(fast!=NULL)
{
fast = fast->next;
if(a == 1)
{
slow= slow->next;
a = 0;
}
else
a = 1;
}
return slow;
}
};