題目描述
輸入一個鏈表踪旷,從尾到頭打印鏈表每個節(jié)點的值。
思路
總共有五種方法狡蝶,如下:
- 將原鏈表的值存在一個棧中绢掰,然后再將棧輸出到另一個vector數組里锄贷。
- 直接將原鏈表的值存在一個vector數組里,最后reverse翻轉一下曼月。
- 每插入一個谊却,都放到最前面,復雜度是$n^{2}$,不是很高效哑芹。
- 通過遞歸到最后一個值炎辨,再一層一層輸入到vector數組里。
- 直接將鏈表翻轉聪姿。
代碼
class Solution {
public:
vector<int>printListFromTailToHead(ListNode*head) {
int digit;
stack<int> f;
vector<int> res;
ListNode *t = head;
while(t != NULL)
{
f.push(t->val);
t = t->next;
}
while(!f.empty())
{
digit = f.top();
f.pop();
res.push_back(digit);
}
return res;
}
};
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
while(head != NULL)
{
res.push_back(head->val);
head = head->next;
}
reverse(res.begin(),res.end());
return res;
}
};
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> res;
if(head != NULL)
{
while(head != NULL)
{
res.insert(res.begin(),head->val);
head = head->next;
}
}
return res;
}
};
class Solution {
public:
vector<int> res;
vector<int> printListFromTailToHead(ListNode* head) {
if(head!=NULL){
printListFromTailToHead(head->next);
res.push_back(head->val);
}
return res;
}
};
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
ListNode *pre = NULL;
ListNode *p = NULL;
while(head != NULL)
{
p = head->next; //p為head的下一個節(jié)點
head->next = pre;//指向前一個節(jié)點
pre = head;//向后移動
head = p;//向后移動
}
while(pre != NULL)
{
res.push_back(pre->val);
pre = pre->next;
}
return res;
}
};