从尾到头打印链表
题目:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
以下使用C++的方法来实现:
- 方法一:遍历链表从尾到头依次输出
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> arr;
ListNode* pCur = head;
ListNode* pTail = NULL;
while(head != pTail)
{
pCur = head;
while (pCur->next != pTail)
{
pCur = pCur->next;
}
arr.push_back(pCur->val);
pTail = pCur;
}
return arr;
}
};
- 方法二:遍历链表,从头到尾输出,最后利用vector中的反向迭代器创建临时对象。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> arr;
ListNode* pCur = head;
while(pCur)
{
arr.push_back(pCur->val);
pCur = pCur->next;
}
return vector<int>(arr.rbegin(),arr.rend()); //反向迭代器创建临时对象
}
};