题目描述:
输入一个链表,从尾到头打印链表每个节点的值。
分析:从尾到头输出,可利用递归来实现。代码如下:
struct ListNode
{
int _val;
struct ListNode* next;
ListNode(int val)
:_val(val)
, next(NULL)
{}
};
//从尾到头打印链表每个节点的值
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> value;
if (head != NULL)
{
value.insert(value.begin(), head->_val);
if (head->next != NULL)
{
vector<int> tmp;
tmp = printListFromTailToHead(head->next);
if (tmp.size() > 0)
value.insert(value.begin(), tmp.begin(), tmp.end());
}
}
return value;
}
int main()
{
struct ListNode s1(1);
struct ListNode s2(2);
struct ListNode* head(&s1);
struct ListNode* p2(&s2);
s1.next = p2;
vector<int> ret = printListFromTailToHead(head);
cout << ret[0] << endl;
cout << ret[1] << endl;
return 0;
}
简洁版本:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> value;
if (head)
{
if (head->next)
{
value = printListFromTailToHead(head->next);
}
value.push_back(head->_val);
}
return value;
}
运行结果: