Sword Finger Offer Interview Question 06. Print a linked list from end to end [Simple]

My solution:

1. Traverse the linked list, save the value in vector <int> ptr, and then traverse ptr in the reverse direction

/**
 * 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. Suddenly found that you can call reverse (ptr.begin (), ptr.end ()). . . A bit cracked

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

Published 65 original articles · Like1 · Visits 486

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105467681