elaine1006 阅读(46) 评论(0)

从尾到头打印链表



import java.util.ArrayList;
import java.util.Stack;


public class PrintListFromTailToHead {
	public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
		
		//方法:使用栈
		Stack<Integer> stack = new Stack<>();
		while(listNode != null){
			stack.add(listNode.val);
			listNode = listNode.next;
		}
		
		ArrayList<Integer> ret = new ArrayList<>();
		while(!stack.isEmpty()){
			ret.add(stack.pop());
		}
		return ret;
		
		
	}
	public static void main(String[] args) {
		ListNode node1 = new ListNode(1);
		ListNode node2 = new ListNode(2);
		ListNode node3 = new ListNode(3);
		ListNode node4 = new ListNode(4);
		node1.next = node2;
		node2.next = node3;
		node3.next = node4;
		ArrayList<Integer> ret = new ArrayList<>();
		ret = printListFromTailToHead(node1);
		System.out.println("反转后:" + ret);
	}


}