LeetCode 从尾到头打印链表 [简单]
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
题目分析
解法1
使用ArrayList<>(),遍历链表,然后拿出数据,在进行反序存储到数组输出
解法2
首先获取元素个数 然后再进行第二次迭代赋值
代码实现
public class ReversePrintListNode {
public static int[] reversePrint2(ListNode head) {
if (head == null) {
return new int[]{};
}
int len = 0;
ListNode temp = head;
while (temp != null) {
len++;
temp = temp.next;
}
int[] result = new int[len];
temp = head;
while (temp != null) {
result[--len] = temp.val;
temp = temp.next;
}
return result;
}
public static int[] reversePrint(ListNode head) {
if (head == null) {
return new int[]{};
}
ListNode temp = head;
ArrayList<Integer> res = new ArrayList<>();
while (temp != null) {
res.add(temp.val);
temp = temp.next;
}
int[] ints = new int[res.size()];
int size = res.size();
for (int i = 0; i <= res.size() - 1; i++) {
ints[--size] = res.get(i);
}
return ints;
}
}
网友评论