您的位置:首页 > Web前端

【剑指offer】从尾到头打印链表

2016-04-09 11:32 435 查看
***************从尾到头打印链表***************************

思路1:借助栈结构来实现:

vector<int> printListFromTailToHead(struct ListNode* head) {
stack<int> vestack;
vector<int> ret;

while (head != NULL)
{
vestack.push(head->val);
head = head->next;
}
while (!vestack.empty())
{
int val = vestack.top();
ret.push_back(val);
vestack.pop();
}
return ret;
}


思路二“:递归实现(递归实现在链表非常长的时候会导致栈溢出的问题。)

vector<int> printListFromTailToHead(struct ListNode* head)
{
vector<int> ret;

if (NULL != head)
{
if (NULL != head->next)
{
printListFromTailToHead(head->next);
}
ret.push_back(head->val);
}
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: