中間ノードLeetcodeのリスト

タイトル説明

最初のノードの単一ヘッドを有する非空リストが与えられると、中間ノードのリストが返されます。

二つの中間ノードがある場合、第二の中間ノードが返されます。

思考

  1. 最初の統計リストのサイズに押し込まスタックを使用し、その後、中間位置にポップアップ表示
  2. サイズに統計情報の配列を使用して、中間の位置に戻します
  3. 指の速度、低速と高速の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;
    }
};
公開された85元の記事 ウォンの賞賛0 ビュー376

おすすめ

転載: blog.csdn.net/weixin_38312163/article/details/105040038