美文网首页
【剑指Offer笔记】:从尾到头打印链表

【剑指Offer笔记】:从尾到头打印链表

作者: w8ed | 来源:发表于2019-04-06 16:45 被阅读0次

    题目描述

    输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

    法一:递归

    include <iostream>

    include <vector>

    using namespace std;

    struct ListNode
    {
    public:
    int val;
    struct ListNode *next;

    /*ListNode(int x) :
    val(x), next(NULL)
    {
    }*/
    

    };

    class Solution
    {
    private:
    vector<int> res;

    public:
    vector<int> printListFromTailToHead(ListNode *head)
    {
    Recurse(head);
    return res;
    }

    void Recurse(ListNode *head)
    {
        if (head)
        {
            Recurse(head->next);
            res.push_back(head->val);
        }
    }
    

    };

    int main()
    {
    ListNode list[4];
    list[0].val = 1;
    list[0].next = &list[1];
    list[1].val = 2;
    list[1].next = &list[2];
    list[2].val = 3;
    list[2].next = &list[3];
    list[3].val = 4;
    list[3].next = NULL;

    Solution solu;
    vector<int> res = solu.printListFromTailToHead(list);
    
    cout << "there are " << res.size() << "datas in vector" << endl;
    for (int i = 0; i < res.size(); i++)
    {
        cout << res[i] << endl;
    }
    cout << system("pause");
    return 0;
    

    }

    法二:利用栈“后进先出”的思路实现

    include <iostream>

    include <vector>

    include <stack>

    using namespace std;

    struct ListNode
    {
    public:
    int val;
    struct ListNode *next;

    /*ListNode(int x) :
    val(x), next(NULL)
    {
    }*/
    

    };

    class Solution
    {
    private:
    vector<int> res;

    public:
    vector<int> printListFromTailToHead(ListNode head)
    {
    stack<int> st;
    ListNode
    cur = head;

        while (cur)
        {
            st.push(cur->val);
            cur = cur->next;
        }
        while(!st.empty())
        {
            res.push_back(st.top());
            st.pop();
        }
        return res;
    }
    

    };

    int main()
    {
    ListNode list[4];
    list[0].val = 1;
    list[0].next = &list[1];
    list[1].val = 2;
    list[1].next = &list[2];
    list[2].val = 3;
    list[2].next = &list[3];
    list[3].val = 4;
    list[3].next = NULL;

    Solution solu;
    vector<int> res = solu.printListFromTailToHead(list);
    
    cout << "there are " << res.size() << "datas in vector" << endl;
    for (int i = 0; i < res.size(); i++)
    {
        cout << res[i] << endl;
    }
    cout << system("pause");
    return 0;
    

    }

    牛客网在线检验:替换空格_牛客网


    参考资料:https://blog.csdn.net/gatieme/article/details/51107632

    相关文章

      网友评论

          本文标题:【剑指Offer笔记】:从尾到头打印链表

          本文链接:https://www.haomeiwen.com/subject/xvgriqtx.html