JZ3 — 从尾到头打印链表

题目描述

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

题目分析

这里的链表指的是从头到尾的单向链表。
使用栈先进后出的特性,从头到尾遍历链表,依次将值push进栈中。最后依次pop即可。
当然,也可以用其他的容器。总体思想是相同的,即先把数据暂时存起来,然后按照要求的顺序输出。

C++

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

Java

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        ArrayList<Integer> ans = new ArrayList<Integer>();
        while (!stack.empty()) {
            ans.add(stack.pop());
        }
        return ans;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部