web页面就是网站吗全网最全搜索引擎app
题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
题目地址:剑指 Offer 06. 从尾到头打印链表 - 力扣(LeetCode)
方法1:栈
思路
题目要求我们将链表的从尾到投打印一下值,那么这种逆序的输出,可以想到用栈,因为栈的特点就是先进后出,我们可以遍历来标,将链表的val放入栈中,再逐个出栈即可。
代码
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
class Solution {public int[] reversePrint(ListNode head) {ListNode p = head;Stack<Integer> stack = new Stack();while (p!=null){stack.add(p.val);p = p.next;}int result[] = new int[stack.size()];int len = stack.size();for (int i = 0; i < len; i++) {result[i] = stack.pop();}return result;}
}
方法2:递归
思路
这个方法是在题解中看到的。
作者:jyd
链接:https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/mian-shi-ti-06-cong-wei-dao-tou-da-yin-lian-biao-d/
利用递归,遍历走到链表的尾巴,再返回去,逐个拿到val,存到集合中即可。相当于用了回溯算法。
算法流程
1. 先走到链表尾部
2.回溯,将节点值加入列表
3.将列表转换成数组,返回数组
代码
class Solution {ArrayList<Integer> tmp = new ArrayList<Integer>();public int[] reversePrint(ListNode head) {recur(head);int[] res = new int[tmp.size()];for(int i = 0; i < res.length; i++)res[i] = tmp.get(i);return res;}void recur(ListNode head) {if(head == null) return;recur(head.next);tmp.add(head.val);}
}