[List] prove safety Offer- face questions 6: list print head from the tail

Title Description

Enter a list, by returning a list sequentially from the tail to the head of ArrayList.

Ideas 1

Traverse the list from beginning to end is relatively simple, while traversing the list, the node element into an array, the array is then set to reverse.

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> v;
        if(head==nullptr)
            return v;
            
        while(head!=nullptr)
        {
            v.push_back(head->val);
            head = head->next;
        }
        vector<int> ans;
        for(int i=v.size()-1; i>=0; i--)
            ans.push_back(v[i]);
        return ans;
    }
};

This method does not change the original list.

Ideas 2

If you change the list, you can set against first-place list, and then traverse the list to the reverse position.

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> v;
        if(head==nullptr)
            return v;
        
        //链表逆置
        ListNode* pre = nullptr;
        ListNode* cur = nullptr;
        while(head!=nullptr)
        {
            cur = head->next;
            head->next = pre;
            pre = head;
            head = cur;
        }
        head = pre;    //注意要head要重新赋值
        
        while(head!=nullptr)
        {
            v.push_back(head->val);
            head = head->next;
        }
        
        return v;
    }
};

Guess you like

Origin www.cnblogs.com/flix/p/12164156.html