工作生活

6.从尾到头打印链表

2019-06-30  本文已影响0人  HamletSunS

思路:
直接顺序打印链表,并入栈,出栈的顺序即为倒序

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> ret;
        if(head==NULL)
            return ret;
        stack<int> st;
        while(head){
            st.push(head->val);
            head=head->next;
        }
        while(!st.empty()){
            ret.push_back(st.top());
            st.pop();
        }
        return ret;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读