剑指offer-从尾到头打印链表

烂漫一生 提交于 2020-01-16 08:29:17

题目描述

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

AC代码

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

typedef struct ListNode
{
    int values;
    struct ListNode *next;
} ListNode, *L;

void ListInsert(L &node)
{
    L p = node;
    L q = new ListNode; //q为要插入的节点
    q->next = NULL;     //
    cin >> q->values;
    while (p->next != NULL)
    {
        p = p->next;
    }
    q->next = p->next;
    p->next = q;
}

void print(L node)
{
    while (node != NULL)
    {
        cout << node->values << endl;
        node = node->next;
    }
}
class Solution
{
public:
    vector<int> printListFromTailToHead(ListNode *head)
    {
        vector<int> result;
        stack<int> s;
        if (head == NULL)
            return result;
        while (head != NULL)
        {
            s.push(head->values);
            head = head->next;
        }
        while (!s.empty())
        {
            // cout << s.top();
            result.push_back(s.top());
            s.pop();
        }
        return result;
    }
    //使用递归实现
    void fun(L node)
    {
        if (node != NULL)
        {
            fun(node->next);
            cout << node->values << endl;
        }
    }
};
int main()
{
    L a;
    a = new ListNode;
    a->next = NULL;
    a->values = 99;

    for (int i = 0; i < 3; i++)
    {
        ListInsert(a);
    }
    print(a);
    cout << "反向输出" << endl;
    Solution A;
    A.fun(a);

    return 0;
}

总结

  • 用栈本质上都可以用递归输出
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!