从尾到头打印链表这里写链接内容
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <vector>
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode* ln = head;
vector<int> v;
while (ln!=NULL)
{
//v.push_back(ln->val); //v[0:4]->5,4,3,2,1 每次放在最后(下标大的)
v.insert(v.begin(),ln->val); //v[0:4]-> 1,2,3,4,5 每次放在最前(下标小的)
ln = ln->next;
}
return v;
}
};
int main()
{
ListNode ln(5);
Solution *s = new Solution();
vector<int> v;
vector<int>::iterator it;
ListNode *node2 = new ListNode(4);
ln.next = node2;
ListNode *node3 = new ListNode(3);
ln.next->next = node3;
ListNode *node4 = new ListNode(2);
ln.next->next->next = node4;
ListNode *node5 = new ListNode(1);
ln.next->next->next->next = node5;
v = s->printListFromTailToHead(&ln);
it = v.begin();
while (it!=v.end())
{
cout << *it << endl;
it++;
}
return 0;
}