输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
输入:head = [1,3,2] 输出:[2,3,1]
解题思路:
package Algriothm; import java.util.Arrays; import java.util.Stack; /** * 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 */ public class Solution1 { public static void main(String[] args) { ListNode head = new ListNode(1); ListNode head1 = new ListNode(3); ListNode head2 = new ListNode(2); head.next = head1; head1.next = head2; int[] ints = reversePrint(head); System.out.println(Arrays.toString(ints)); } public static int[] reversePrint(ListNode head) { ListNode cur = head; Stack<Integer> stack = new Stack<Integer>(); while (cur != null) { stack.push(cur.val); cur = cur.next; } int[] res = new int[stack.size()]; int size = stack.size(); for (int i = 0; i < size; i++) { res[i] = stack.pop(); } return res; } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
原文:https://www.cnblogs.com/yssd/p/15153927.html