从尾到头打印链表_牛客题霸_牛客网
注意题目给的链表是无头的
解答
思路一
使用栈的思想就行了
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
stack<int> st;
while(head)
{
st.push(head->val);
head = head->next;
}
while(!st.empty())
{
ret.push_back(st.top());
st.pop();
}
return ret;
}
};
思路二
数组逆序
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
while(head)
{
ret.push_back(head->val);
head = head->next;
}
reverse(ret.begin(),ret.end());
return ret;
}
};
思路三
递归第一种写法,难看死了0.0
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
void recursion(const ListNode* head, vector<int>& v)
{
if(head->next)
{
recursion(head->next,v);
}
v.push_back(head->val);
}
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
if(head)
{
recursion(head,ret);
}
return ret;
}
};
递归第二种写法,好看多了
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
recursion(head,ret);
return ret;
}
void recursion(ListNode* head,vector<int>& v)
{
if(!head)
return;
recursion(head->next,v);
v.push_back(head->val);
}
};