剑指offer06 从尾到头打印链表

169 阅读1分钟

题目

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 示例 1:

输入: head = [1,3,2]
输出: [2,3,1]

 

限制:

0 <= 链表长度 <= 10000

思路

reverse 函数

将链表的数据源是储存在vector数组中,再使用reverse函数反转数组就行。
有一点,这里头指针指向的是首元结点。

/**
 * 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> ans;
        while(head) {
            ans.push_back(head->val);
            head = head->next;
        }
        reverse(ans.begin(),ans.end());//使用reverse函数
        return ans;
    }
    
};

递归处理

递归找到每个元素,从后回溯存在数组中

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    void df(ListNode* node) {
        if(!node) return;//判断条件:空链表返回
        df(node->next);
        res.push_back(node->val);
    }

    vector<int> reversePrint(ListNode* head) {
        df(head);
        return res;
    }
};

辅助栈

还可以用一个辅助栈来实现:

/**
 * 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> res;
        stack<int> temp;
        while(head) {
            temp.push(head->val);
            head = head->next;
        }

        while(!temp.empty()) {
            res.push_back(temp.top());
            temp.pop();
        }
            
        return res;
    }
};