题目描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
解题思路:1)将链表遍历一遍(需要中间temp链表),记录下链表的长度并创建同样长度的数组;继续遍历链表,将链表数值 按照倒序放到数组中
2)没有实现:学习一下链表的尾插法?将链表变为一个倒序之后的新链表!
链表中有两部分内容:1.value具体的数值;2.next指针在java语言中存储的为地址值
手写代码:
class Solution {
public int[] reversePrint(ListNode head) {
ListNode temp = head;
int i = 0;
while(temp != null){
i++;
temp = temp.next;
}
int[] val = new int[i];
temp = head;
for(int j = i-1;j >=0 ;j--){
val[j] = temp.val;
temp = temp.next;
}
return val;
}
}
答案代码:答案中有用到栈结构,利用栈的先入后出的特性,先将链表数据放到栈中,再依次pop放入数组;
使用递归的方式,递归需要自己创建一个方法
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
while (temp != null) {
stack.push(temp);
temp = temp.next;
}
int size = stack.size();
int[] print = new int[size];
for (int i = 0; i < size; i++) {
print[i] = stack.pop().val;
}
return print;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/mian-shi-ti-06-cong-wei-dao-tou-da-yin-lian-biao-b/
来源:力扣(LeetCode)