算法练习(二):从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
输入: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;
}
}
浙公网安备 33010602011771号