剑指 Offer 06. 从尾到头打印链表
一、题目详情
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= list.length <= 10000
二、暴力法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
int length = 0;
ListNode temp = head;
while(temp != null){
length++;
temp = temp.next;
}
int[] arr = new int[length];
temp = head;
for(int i = length - 1;i >= 0;i--){
arr[i] = temp.val;
temp = temp.next;
}
return arr;
}
}
三、哈希表法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
List<Integer> list = new ArrayList<>();
ListNode temp = head;
while(temp != null){
list.add(temp.val);
temp = temp.next;
}
int[] arr = new int[list.size()];
for(int i = list.size() - 1;i >= 0;i--){
arr[list.size() - i - 1] = list.get(i);
}
return arr;
}
}
四、辅助栈法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> stack = new LinkedList<>();
while(head != null){
stack.addLast(head.val);
head = head.next;
}
int[] arr = new int[stack.size()];
for(int i = 0;i < arr.length;i++){
arr[i] = stack.removeLast();
}
return arr;
}
}