输入一个链表,从尾到头打印链表每个节点的值。
思路:用insert函数每次扫描一个节点,将该结点数据存入vector中,如果该节点有下一节点,将下一节点数据直接插入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> vec;
if(head!=NULL){
vec.insert(vec.begin(),head->val);//在最前面插入新元素
while (head->next!=NULL)
{
vec.insert(vec.begin(),head->next->val);
head=head->next;
}
}
return vec;
}
};
剑指offer上提到使用栈。把结点放入栈中,遍历完成后,再从栈顶开始逐个输出结点的值,此时输出结点的顺序已经反转过来了。
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
//利用栈
vector<int> vec;
stack <int> sta;
ListNode *pNode=head;//遍历到的节点
while (pNode!=NULL){
sta.push(pNode->val);
pNode=pNode->next;
}
while(!sta.empty()) {
vec.push_back(sta.top());
sta.pop();
}
return vec;
}
};