从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
解题思路
1、建一个长度为10000的数组,太耗资源!!!十分不可取!
2、思考了一下,由于对象数量不确定,需要在容量不足的时候进行自动扩充,则需要使用集合。使用集合保存结点中的值,最后新建length+1长度的数组,将集合中的值逆取放入数组中(见代码1)。
3、充分利用堆的性质,先进后出(见代码2)。
代码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) {
if(head == null){
return new int[0];
}
List<Integer> list = new ArrayList<Integer>();
int length = 0;
list.add(head.val);
while(head.next != null){
length++;
list.add(head.next.val);
head = head.next;
}
int[] val = new int[length+1];
for(int i=0;i<length+1;i++){
val[i] = list.get(length-i);
}
return val;
}
}
代码2
/**
* 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<ListNode> stack = new Stack<ListNode>();
while(head != null){
stack.push(head);
head = head.next;
}
int length = stack.size();
int[] arr = new int[length];
for(int i = 0;i<length; i++){
arr[i] = stack.pop().val;
}
return arr;
}
}