Realize the reverse order of the linked list C++

Problem Description

Enter a linked list and return an ArrayList in the order from the end to the beginning of the linked list.

enter

{
    
    67,0,24,58}

return value

[58,24,0,67]
#include<iostream>
using namesapce std;
struct ListNode {
    
    
        int val;
        struct ListNode *next;
        ListNode(int x) :
             val(x), next(NULL) {
    
    
        }
 };

class Solution {
    
    
public:
    vector<int> printListFromTailToHead(ListNode* head) {
    
    
        vector<int> requene;
        ListNode *p=NULL;
        p=head;
        stack<int> stk;
        while(p!=NULL){
    
    
            stk.push(p->val);
            p=p->next;
        }
        while(!stk.empty()){
    
    
            requene.push_back(stk.pop());
            stk.pop();
        }
        return requene;
    }
};

Guess you like

Origin blog.csdn.net/p715306030/article/details/114712794