Sword Finger Offer Interview Question 06.リンクされたリストを端から端まで印刷する[シンプル]

私の解決策:

1.リンクリストを走査し、値をベクトル<int> ptrに保存してから、ptrを逆方向に走査します。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> ptr;
        vector<int> res;
        if(head==nullptr)   return res;
        while(head){
            ptr.push_back(head->val);
            head=head->next;
        }
        for(int i=ptr.size()-1;i>=0;i--)
            res.push_back(ptr[i]);
        return res;
    }
};

2.突然リバース(ptr.begin()、ptr.end())を呼び出せることがわかりました。少し割れた

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> ptr;
        vector<int> res;
        if(head==nullptr)   return res;
        while(head){
            ptr.push_back(head->val);
            head=head->next;
        }
        reverse(ptr.begin(),ptr.end());
        return ptr;
    }
};

オリジナルの記事を65件公開 Like1 Visits 486

おすすめ

転載: blog.csdn.net/qq_41041762/article/details/105467681