【剑指offer】从尾到头打印链表 -- Java实现

mac2024-04-10  33

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

public class Node { int val; Node next = null; Node(int val) { this.val = val; } }

分析

listNode 是链表,只能从头遍历到尾,但是输出却要求从尾到头,这是典型的"先进后出",我们可以想到栈! ArrayList 中有个方法是 add(index,value),可以指定 index 位置插入 value 值 所以我们在遍历 listNode 的同时将每个遇到的值插入到 list 的 0 位置,最后输出 listNode 即可得到逆序链表

public class Solution { public ArrayList<Integer> printListFromTailToHead(Node n){ ArrayList<Integer> res = new ArrayList<Integer> (); Node tmp = n; while (tmp != null){ res.add(0,tmp.val); tmp = tmp.next; } return res; } } public class text { public static void main(String[] args) { Solution s = new Solution(); Node n = new Node(1); Node n1 = new Node(2); Node n2 = new Node(3); Node n3 = new Node(4); Node n4 = new Node(5); n.next = n1; n1.next = n2; n2.next = n3; n3.next = n4; List l = s.printListFromTailToHead(n); System.out.println(l); } }
最新回复(0)