老生长谈,从头打印一个链表。也不是什么难题,单向链表只能从头走到尾。从尾到头打印很明显的先进后出性质。即可以用一个栈来装遍历结果,也可以用递归来解。总之,本质上都是用一个链表模拟栈。
- 用栈的解法
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
#include <stack>
#include <vector>
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> stackp;
vector<int> vec;
ListNode* p = head;
while(p)
{
stackp.push(p->val);
p=p->next;
}
p = head;
while(p)
{
vec.push_back(stackp.top());
stackp.pop();
p=p->next;
}
return vec;
}
};
*递归的解法(缺点,链表过长容易溢出)
#include <vector>
class Solution {
public:
vector<int> vec;
vector<int> printListFromTailToHead(ListNode* head) {
if(head == NULL)
return vec;
printListFromTailToHead(head->next);
vec.push_back(head->val);
return vec;
}
};