从头到尾打印链表(Java实现)

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

解题思路
利用栈“先入后出”的特性。

代码实现:

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

猜你喜欢

转载自blog.csdn.net/melwx/article/details/88071867