输入一个链表,从尾到头打印链表每个节点的值。
但是 根据往常的经验 如果if里面有return了 就不要写else了
import java.util.ArrayList;
import java.util.Stack; class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
} public class FromTailToHead {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(null==listNode ){
return list;
} Stack<Integer> stack = new Stack<Integer>();
ListNode nextNode = listNode;
while(null!=nextNode){
stack.push(nextNode.val);
nextNode = nextNode.next;
}
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
}
下面是递归调用
/*
* 递归实现
*/
public class FromTailToHead2 {
public static void printListFromTailToHead(ListNode Head) {
if(null!=Head){
if(null!=Head.next){
printListFromTailToHead(Head.next);
}
System.out.print(Head.val+"\t");
}
} public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
n1.next=n2;
n2.next=n3;
n3.next=null;
ListNode Head =n1;
while(Head!=null){
System.out.print(Head.val+"\t");
Head=Head.next;
}
System.out.println();
printListFromTailToHead(n1); }
}