您的位置:首页 > Web前端

剑指offer-倒序打印链表

2017-04-03 14:24 399 查看
重点提示

面试过程中若需要修改输入的数据,可以提前问面试官是否允许做修改;

需要考虑程序的鲁棒性(其实就是容不容易崩);

当遇到逆序情况时,要联想到栈的性质,先进后出,后进先出;
typedef struct linkList
{
int data;
struct linkList *next;
}ListNode;
void ReversinglyPrint(ListNode *phead)
{
std::stack<ListNode *> nodes;
ListNode *p = phead;
while (p!= NULL)
{
nodes.push(p);
p = p->next;
}
while (!nodes.empty())
{
p = nodes.pop();
printf("%d  ", p->data);
nodes.pop();
}
}


用reverse函数;

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