剑指offer-倒序打印链表

来源:互联网 发布:蚕丝被淘宝评价 编辑:程序博客网 时间:2024/05/20 18:18
  • 重点提示
    面试过程中若需要修改输入的数据,可以提前问面试官是否允许做修改;
    需要考虑程序的鲁棒性(其实就是容不容易崩);
    当遇到逆序情况时,要联想到栈的性质,先进后出,后进先出;
    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;    }};


0 0