剑指offer的66题之第3题:从尾巴到头打印链表
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
代码:
1、递归方法:
1 class Solution { 2 public: 3 vector<int> printListFromTailToHead(struct ListNode* head) { 4 vector<int> value; 5 if(head != NULL) 6 { 7 value.insert(value.begin(),head->val); 8 if(head->next != NULL) 9 { 10 vector<int> tempVec = printListFromTailToHead(head->next); 11 if(tempVec.size()>0) 12 value.insert(value.begin(),tempVec.begin(),tempVec.end()); 13 } 14 15 } 16 return value; 17 } 18 };
2、调用库函数
1 /** 2 * struct ListNode { 3 * int val; 4 * struct ListNode *next; 5 * ListNode(int x) : 6 * val(x), next(NULL) { 7 * } 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> printListFromTailToHead(struct ListNode* head) { 13 vector<int> value; 14 if(head != NULL) 15 { 16 value.insert(value.begin(),head->val); 17 while(head->next != NULL) 18 { 19 value.insert(value.begin(),head->next->val); 20 head = head->next; 21 } 22 23 } 24 return value; 25 } 26 };
注意:
1、判断传入的参数是否为空!若为空返回空!如下,可以直接返回没有初始化的value!
vector<int> value;
if(head != NULL)
{
}
return value;
2、即使自定义变量,给它赋值,下一步对该变量操作时候,还是要判断赋予的值是否是空的!
3、注意vector类型变量的insert用法,还有value.begin()和value.end()用法
4、链表的终止条件:head->next != NULL