本質是一個反轉單鏈表
題目描述
輸入一個鏈表,按鏈表從尾到頭的順序返回一個ArrayList。
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
解法1:鏈表逆置
最直接想到的就是用三個指針逆置鏈表,然後打印(數組尾插)
注意:函數返回值是一個數組,所以最終要輸出一個數組
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> ret;
if (head == NULL) return ret;
ListNode* pre = NULL;
ListNode* cur = head->next;
while (cur)//逆置
{
head->next = pre;
pre = head;
head = cur;
cur = cur->next;
}
head->next = pre;
while (head)//打印
{
ret.push_back(head->val);
head = head->next;
}
return ret;
}
};
解法2:出入棧
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
stack<int> s;
vector<int> v;
//讓節點的值入棧
while(head)
{
s.push(head->val);
head=head->next;
}
//出棧
while(!s.empty())
{
v.push_back(s.top());
s.pop();
}
return v;
}
};
解法3:遞歸
void printListFromTailToHead(ListNode* head)
{
if (head == NULL) return;
if (head->next)
printListFromTailToHead(head->next);
printf("%d ", head->val);
}
解法4:應用vector中的反向迭代器
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> v;
while(head)
{
v.push_back(head->val);
head=head->next;
}
return vector<int>(v.rbegin(),v.rend());
}
};