您的位置:首页 > 职场人生

面试题:从尾到头打印链表

2016-10-21 16:30 204 查看
题目:输入一个链表的头结点,从尾到头反过来打印出每个节点的值。

方法1:使用栈
/*
链表节点定义如下:
struct ListNode
{
int _data;
ListNode* _next;
};
*/

void PrintListTailToHead(ListNode* phead)
{
assert(phead);

stack<ListNode*> s;
ListNode* cur = phead;
while (cur)
{
s.push(cur);
cur = cur->_next;
}

while (!s.empty())
{
cout<<s.top()->_data<<" ";
s.pop();
}
cout<<endl;
}


方法2:递归
void PrintListTailToHead(ListNode* phead)
{
if (phead == NULL)
{
return;
}

PrintListTailToHead(phead->_next);

cout<<phead->_data<<" ";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表