题目描述
输入一个链表,从尾到头打印链表每个节点的值。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> var;
while(head != NULL)
{
var.insert(var.begin(), head->val);
head = head->next;
}
return var;
}
};
解题思路方法一:链表从尾到头输出,利用递归实现,不使用库函数直接printf输出的时候用递归比较好
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> value;
if(head != NULL)
{
value.insert(value.begin(),head->val);
if(head->next != NULL)
{
vector<int> tempVec = printListFromTailToHead(head->next);
if(tempVec.size()>0)
value.insert(value.begin(),tempVec.begin(),tempVec.end());
}
}
return value;
}
};
方法二:用库函数,每次扫描一个节点,将该结点数据存入vector中,如果该节点有下一节点,将下一节点数据直接插入vector最前面,直至遍历完,或者直接加在最后,最后调用reverse
链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
来源:牛客网
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> value;
if(head != NULL)
{
value.insert(value.begin(),head->val);
while(head->next != NULL)
{
value.insert(value.begin(),head->next->val);
head = head->next;
}
}
return value;
}
};
补充
vector中insert用法
iterator insert( iterator loc, const TYPE &val );
void insert( iterator loc, size_type num, const TYPE &val );
void insert( iterator loc, input_iterator start, input_iterator end );
insert() 函数有以下三种用法:
在指定位置loc前插入值为val的元素,返回指向这个元素的迭代器,
在指定位置loc前插入num个值为val的元素
在指定位置loc前插入区间[start, end)的所有元素 .
来源:https://blog.youkuaiyun.com/xiadasong007/article/details/4031184