【Jianzhi 06】Print the linked list from beginning to end

Method 1: Auxiliary stack: time O(n), space O(n)

Problem solution: using the first-in-last-out feature of the stack, first traverse the linked list and push the stack, then pop the stack and put the elements into the array

class Solution {
    
    
public:
    vector<int> reversePrint(ListNode* head) 
    {
    
    
    	if (head == NULL)
    		return vector<int>();
        vector<int> res;
        stack<int> stc;
        while (head != NULL)
        {
    
    
            stc.push(head->val);
            head = head->next;
        }
        while (!stc.empty())
        {
    
    
            res.push_back(stc.top());
            stc.pop();
        }
        return res;
    }
};

Method 2: Recursion: time O(n), space O(n)

Problem solution: when backtracking, add elements to the array

class Solution {
    
    
public:
    vector<int> res;
    void dfs(ListNode* root)
    {
    
    
        if (root == NULL)
            return;
        dfs(root->next);
        res.push_back(root->val);
    }
    vector<int> reversePrint(ListNode* head) 
    {
    
    
        dfs(head);
        return res;
    }
};

Method 3: Invert the linked list: time O(n), space O(n)

Problem solution: first invert the linked list, then traverse the linked list to insert data

class Solution {
    
    
public:
    vector<int> reversePrint(ListNode* head) 
    {
    
    
        if (head == NULL)
            return vector<int>();
        ListNode* cur = head;
        ListNode* pre = head->next;
        cur->next = NULL;
        while (pre != NULL)
        {
    
    
            cur = pre;
            pre = pre->next;
            cur->next = head;
            head = cur;
        }
        vector<int> res;
        while (head != NULL)
        {
    
    
            res.push_back(head->val);
            head = head->next;
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/112362709