import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;
/**
* @Class ReversePrint
* @Description 剑指 Offer 06. 从尾到头打印链表
* 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
*
* 示例 1:
* 输入:head = [1,3,2]
* 输出:[2,3,1]
*
* 限制:
* 0 <= 链表长度 <= 10000
* @Author
* @Date 2020/6/28
**/
public class ReversePrint {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}
/**
* 解法1:利用栈
*/
public static int[] reversePrint(ListNode head) {
ListNode listNode = head;
Stack<Integer> integerDeque =new Stack<>();
int count =0;
while (listNode!= null){
integerDeque.push(listNode.val);
listNode = listNode.next;
count++;
}
int[] ans = new int[count];
for (int i = 0; i <count ; i++) {
ans[i] = integerDeque.pop();
}
return ans;
}
/**
* 解法2:利用递归
*/
public static int[] reversePrint(ListNode head) {
LinkedList<Integer> linkedList = new LinkedList<>();
reversePrint(head,linkedList);
int size = linkedList.size();
int[] ans = new int[size];
for (int i = 0; i < size; i++) {
ans[i]= linkedList.pop();
}
return ans;
}
private static LinkedList<Integer> reversePrint(ListNode listNode, LinkedList linkedList){
if(listNode==null) return null;
linkedList.add(listNode.val);
return reversePrint(listNode.next,linkedList);
}
// 测试用例
public static void main(String[] args) {
ListNode listNode11 = new ListNode(1);
ListNode listNode12 = new ListNode(3);
listNode11.next = listNode12;
ListNode listNode13 = new ListNode(2);
listNode12.next = listNode13;
listNode13.next = null;
int[] ans = reversePrint(listNode11);
System.out.println("demo01 result:");
for (int val : ans){
System.out.print(" "+val);
}
System.out.println("");
}