从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2]输出:[2,3,1]
两种解法:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/class Solution {public int[] reversePrint(ListNode head) {/***解法二:Stack*/Stack<Integer> stack = new Stack<Integer>();int size = 0; //数组长度while(head != null){stack.push(head.val);head = head.next;size++;}int[] ans = new int[size];for(int i = 0; i < size; i++){ans[i] = stack.pop();}return ans;/***解法一*//**ListNode temp = head;int length = 0;while(head != null){length++;head = head.next;}int[] ans = new int[length];for (int i = length-1; i >= 0; i--){ans[i] = temp.val;temp = temp.next;}return ans;**/}}
