输入一个链表,从尾到头打印链表每个节点的值。
package test1;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
public class JZoffer3 {
public static void main(String[] args) {
ListNode head=null;
ListNode con=null;
Scanner sc=new Scanner(System.in);
int n=0;
System.out.println("输入链表中结点的个数:");
n=sc.nextInt();
for(int i=0;i<n;i++) {
ListNode node=new ListNode(sc.nextInt());
if(con!=null)
con.next=node;
con=node;
if(i==0) {
head=con;
}
}
if(head!=null) {
ArrayList array=printListFromTailToHead(head);
for(int i=0;i<n;i++) {
System.out.println(array.get(i));
}
}
}
private static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> sta=new Stack<>();
ArrayList<Integer> array=new ArrayList<>();
while(listNode!=null) {
sta.push(listNode.val);
listNode=listNode.next;
}
while(!sta.empty()) {
array.add(sta.pop());
}
return array;
}
}