40 lines
885 B
Java
Executable File
40 lines
885 B
Java
Executable File
package com.thinker.bishi.offer;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.Stack;
|
|
|
|
class ListNode {
|
|
int val;
|
|
ListNode next = null;
|
|
ListNode(int val) {
|
|
this.val = val;
|
|
}
|
|
}
|
|
public class PrintListFromTailToHead{
|
|
|
|
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode){
|
|
ArrayList<Integer> lists = new ArrayList<Integer>();
|
|
Stack<Integer> stack = new Stack<Integer>();
|
|
while(listNode != null){
|
|
stack.push(listNode.val);listNode = listNode.next;
|
|
}
|
|
while(!stack.isEmpty()){
|
|
lists.add(stack.pop());
|
|
}
|
|
|
|
return lists;
|
|
}
|
|
|
|
public static void main(String[] args){
|
|
ListNode root = new ListNode(1);
|
|
root.next = new ListNode(2);
|
|
root.next.next = new ListNode(3);
|
|
ArrayList<Integer> result = printListFromTailToHead(root);
|
|
for(int i=0;i < result.size();i++ ){
|
|
System.out.print(result.get(i)+"\t");
|
|
}
|
|
System.out.println();
|
|
}
|
|
}
|
|
|