import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
class Node{
int data;
public Node(int data){
this.data=data;
}
Node next=null;
}
public class 面试题5_从尾到头打印链表 {
/*题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
笔
*/
static Node head=null;
public static void main(String[] args) {
head=new Node(1);
head.next=new Node(2);
head.next.next=new Node(3);
head.next.next.next=new Node(4);
Node p=head;
while(p!=null){
System.out.print(p.data+" ");
p=p.next;
}
System.out.println();
Node head1=null;
printList(head);
System.out.println();
printByStack(head);
}
public static ArrayList<Integer> printByStack(Node head){
Stack st=new Stack<Integer>();
Node p=head;
while(p!=null){
st.push(p.data);
p=p.next;
}
ArrayList<Integer> list=new ArrayList<Integer>();
while(!st.isEmpty()){
//System.out.print(st.pop()+" ");
list.add((Integer)st.pop());
}
return list;
}
public static void printList(Node head){
if(head!=null){
printList(head.next);
System.out.print(head.data+" ");
}
}
}