Skip to content

Latest commit

 

History

History
91 lines (77 loc) · 1.78 KB

从尾到头打印链表.md

File metadata and controls

91 lines (77 loc) · 1.78 KB

题目链接:从尾到头打印链表

从尾到头打印链表

题目描述

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

思路

利用栈或者递归实现,或者直接一个reverse

代码

reverse版:

#include <bits/stdc++.h>
using namespace std;

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

class Solution
{
  public:
    vector<int> printListFromTailToHead(ListNode *head)
    {
        vector<int> ans;
        if (head == NULL)
            return ans;
        while (head->next != NULL)
        {
            ans.push_back(head->val);
            head = head->next;
        }
        ans.push_back(head->val);
        reverse(ans.begin(), ans.end());
        return ans;
    }
};
int main()
{
    Solution ac;
    ListNode n1(1), n2(1), n3(1);
    n1.val = 1, n2.val = 2, n3.val = 3;
    n1.next = &n2;
    n2.next = &n3;
    n3.next = NULL;
    vector<int> ans = ac.printListFromTailToHead(&n1);
    for (auto num : ans)
        cout << num << " ";
    cout << endl;
    return 0;
}

递归版(短小精悍):

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution
{
  public:
    vector<int> ans;
    vector<int> printListFromTailToHead(ListNode *head)
    {
        if (head != NULL)
        {
            if (head->next != NULL)
                printListFromTailToHead(head->next);
            ans.push_back(head->val);
        }
        return ans;
    }
};