剑指offer题目3:从尾到头打印链表。
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
解答思路
这题很典型的考到了链表反转。
从这题我立刻去查了一下链表反转是怎么做的,最简单的就是用递归。
function revert(ListNode head) {
if (head != NULL && head->next != NULL) {
revert(head->next);
head->next->next = head;
head->next = NULL;
}
}
实现代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> value;
if(head != NULL) {
value.insert(value.begin(), head->val);
if(head->next != NULL) {
vector<int> other = printListFromTailToHead(head->next);
value.insert(value.begin(),other.begin(),other.end());
}
}
return value;
}
};
作者:大傻逼
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。