从尾到头打印链表
题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例
1 2
| 输入: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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class Solution { public int[] reversePrint(ListNode head) { if (head == null) return new int[0]; Deque<Integer> stack = new ArrayDeque<>(); ListNode currentNode = head; while (currentNode != null) { stack.push(currentNode.val); currentNode = currentNode.next; } int size = stack.size(); int[] result = new int[size]; for (int i = 0; i < size; i++) { result[i] = stack.pop(); } return result; } }
|
但是栈的操作很耗时,在 LeetCode 的提交中消耗了 2 ms 来执行。
解法二
先遍历数组的长度,然后开辟一个数组来存放倒序的链表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
class Solution { public int[] reversePrint(ListNode head) { if (head == null) return new int[0]; int length = 0; ListNode currentNode = head; while (currentNode != null) { length++; currentNode = currentNode.next; } int[] result = new int[length]; int index = length - 1; currentNode = head; while (currentNode != null) { result[index] = currentNode.val; index--; currentNode = currentNode.next; } return result; } }
|