[剑指Offer]从尾到头打印链表(CC++描述)

题目描述 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vectorint printListFromTailToHead(ListNode* head) {
        vectorint ret;
        if(head == NULL)
            return ret;
        stackint st;
        ListNode* tmp = head;
        while(tmp != NULL)
        {
            st.push(tmp-val);
            tmp = tmp-next;
        }
        while(!st.empty())
        {
            ret.push_back(st.top());
            st.pop();
        }
        return ret;
    }
};
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vectorint printListFromTailToHead(struct ListNode* head) {
        vectorint vec;
        printListFromTailToHead(head,vec);
        return vec;
    }
    void printListFromTailToHead(struct ListNode* head,vectorint vec)
    {
        if(head!=nullptr)
        {
            if(head-next!=nullptr)
            {
                printListFromTailToHead(head-next,vec);
            }
            vec.push_back(head-val);
        }
    }
};
最新回复(0)
/jishuyuCowjg6lnNyV3C_2FxCBMdPwgDS2itnCddTi3bg_3D_3D4795349
8 简首页