【剑指06】从头到尾打印链表

方法一:辅助栈:时间O(n),空间O(n)

题解:利用栈的先进后出特性,先遍历链表进行入栈,随后出栈并把元素放入数组

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;
    }
};

方法二:递归:时间O(n),空间O(n)

题解:在回溯的时候,添加元素到数组中

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;
    }
};

方法三:逆置链表:时间O(n),空间O(n)

题解:先逆置链表,再遍历链表插入数据

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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_45691748/article/details/112362709