Sword refers to Offer 06. Print the linked list from end to beginning (simple)【stack】

topic:

Insert picture description here


Code:

/**
 * 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) {
    
    
        stack<int> s;
        vector<int> ans;
        while(head!=NULL)
        {
    
    
            s.push(head->val);
            head=head->next;
        }
        
        while(s.size())
        {
    
    
            ans.push_back(s.top());
            s.pop();
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45260385/article/details/110097354