2020-06-22
1.題目描述
輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。
2.題解
1.放入vector中,然後reverse
2.將鏈表反轉
3.代碼
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int>tmp;
ListNode* p=head;
while (p){
tmp.push_back(p->val);
p=p->next;
}
reverse(tmp.begin(),tmp.end());
return tmp;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
if (!head) return vector<int>(0);
vector<int>tmp;
ListNode* pre=head,*p=pre->next,*t;
pre->next=NULL;
while (p){
t=p->next;
p->next=pre;
pre=p;
p=t;
}
while (pre){
tmp.push_back(pre->val);
pre=pre->next;
}
return tmp;
}
};