题目从头到尾的输出链表
package javafirst;
import java.util.ArrayList;
import java.util.Stack;
//1.利用栈实现的从尾到头打印链表
public class Solution{
public ArrayList<Integer> reversePrintln(ListNode listNode)
{ Stack <Integer> t= new Stack<>();
while(listNode!=null)
{t.push(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> list = new ArrayList<>();
while(!list.isEmpty())
{list.add(t.pop());
}
return list;
}
//自己定义链表
public class ListNode
{
int val;
ListNode next;
public ListNode(int x){
val=x;
}
}
//2.递归版本,利用递归实现
ArrayList<Integer> arrayList=new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode!=null){
printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}