标签:bsp span java his describe node rgs head add
class ListNode
{
int val;
ListNode next = null;
ListNode(int val)
{
this.val = val;
}
}
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
LinkedList<Integer> stack = new LinkedList<Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
//入栈
ListNode point = listNode;
while(point != null){
stack.addFirst(point.val);
point = point.next;
}
//出栈
while(stack.size() > 0){
result.add(stack.removeFirst());
}
return result;
}
}
2、利用递归,非常巧妙
import java.util.*;
class ListNode
{
int val;
ListNode next = null;
ListNode(int val)
{
this.val = val;
}
}
public class Solution {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode)
{
/*
*递归
*/
if (listNode != null)
{
this.printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
public static void main(String[] args)
{
ListNode listNode = new ListNode(2);
listNode.next = new ListNode(3);
listNode.next.next = new ListNode(4);
listNode.next.next.next = new ListNode(0);
Solution s = new Solution();
System.out.println(s.printListFromTailToHead(listNode));
}
}
标签:bsp span java his describe node rgs head add
原文地址:http://www.cnblogs.com/code666/p/7205100.html