【剑指offer】【链表】06.从尾到头打印链表

题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

改变链表

先逆置链表,然后将结果保存到数组中

/**
 * 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) {
        ListNode *new_head = nullptr;
        while(head)
        {
            ListNode* next = head->next;
            head->next = new_head;
            new_head = head;
            head = next;   
        }      
        vector<int> v;
        while(new_head)
        {
            v.push_back(new_head->val);
            new_head = new_head -> next;
        }
        return v;
    }
};

reverse

依次将链表保存到数组中,然后逆置数组

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> v;
        ListNode* cur = head;
        while (cur) {
            v.push_back(cur->val);
            cur = cur->next;
        }
        reverse(v.begin(), v.end());
        return v;
    }
};

依次遍历链表并入栈,然后栈中元素依次弹到数组中

/**
 * 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> v;
        stack<int> s;
        //入栈
        while(head){
            s.push(head->val);
            head = head->next;
        }
        //出栈
        while(!s.empty()){
            v.push_back(s.top());
            s.pop();
        }
        return v;
    }
};

递归

/**
 * 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) {
        if(!head)
            return {};
        vector<int> v = reversePrint(head->next);
        v.push_back(head->val);
        return v;
    }
};

posted @ 2020-04-06 21:25  NaughtyCoder  阅读(92)  评论(0)    收藏  举报