Sword refers to Offer series Sword refers to Offer 06: Print the linked list from end to beginning

Title description:

Enter the head node of a linked list, and return the value of each node from the end to the beginning (return with an array).

Example:

Input: head = [1,3,2]
Output: [2,3,1]

My thoughts:

Use the recursive method to recurse until the linked list is empty, and then store the recursive node value into the array each time, and then return.

Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    vector<int> reversePrint(ListNode* head) {
    if(head == nullptr)
        return res;
    reversePrint(head->next);
    res.push_back(head->val);
    return res;
    }
};

Another method I looked at:

Use the array directly, first store each data in the linked list into the array through traversal, and then directly use the function to reverse the array, which is very fast

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    vector<int> reversePrint(ListNode* head) {
    while(head)
    {
        res.push_back(head->val);
        head = head ->next;
    }
    reverse(res.begin(),res.end());
    return res;
    }
};

 

Guess you like

Origin blog.csdn.net/qq_46423166/article/details/110791837