题目
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路一
- 遍历链表,每个节点的值存到数组中。
- 将数组中的元素反转。
代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
if ( head == nullptr ) return res;
while ( head != nullptr ) {
res.push_back( head->val );
head = head->next;
}
int start = 0, end = res.size() - 1;
while ( start < end ) {
int tmp = res[start];
res[start] = res[end];
res[end] = tmp;
++start;
--end;
}
return res;
}
};
思路二
- 遍历链表,将链表的节点保存到栈中。
- 栈吐出结点直到为空,依次将节点的值保存到数组中。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
if ( head == nullptr ) return res;
stack<ListNode*> s;
while ( head != nullptr ) {
s.push( head );
head = head->next;
}
ListNode* node = nullptr;
while ( !s.empty() ) {
node = s.top();
s.pop();
res.push_back( node->val );
}
return res;
}
};