【在线oj实现】
【递归实现】
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> temp;
if (head == NULL)//如果为空链表
{
return{};
}
else if (head->next == NULL)//如果链表只有一个结点
{
return{ head->val };
}
if (head != NULL)
{
printListFromTailToHead(head->next);//递归实现
temp.push_back(head->val);
}
return temp;
}
};
【利用栈非递归实现】
#include<stack>
#include<assert.h>
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;
stack<int> s;
ListNode* cur = head;
while (cur != NULL)//先将每个结点压进栈中--->先进后出
{
s.push(cur->val);
cur = cur->next;
}
while (!s.empty())
{
v.push_back(s.top());//依次将栈中的数据取出来放进临时数组中
s.pop();
}
return v;
}
};