原网址:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
方法一:利用栈的方法
将头和尾调换的方法,和栈的先进后出的思想很相似。
可以看遍历列表,把列表里的元素存入到栈中(入栈push);然后在逐个取出放入结点(出栈pop)
-
Stack的基本使用初始化:Stack stack=new Stack
-
判断是否为空:stack.empty()
-
取栈顶值(不出栈):stack.peek()
-
进栈:stack.push(Object);
-
出栈:stack.pop();
Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> st =new Stack<ListNode>();//定义一个栈
ListNode node = head; //定义一个“指针”
while(node!=null) {
st.push(node); //如果结点不为空,就将它推入栈
node=node.next; //“指针”指向下一个结点
}
int size = st.size();
int[] newList = new int[size];//定义一个数组,数组长度为栈中存在的元素数
for (int i = 0; i < size; i++) {
newList[i] = st.peek().val;//将栈顶元素赋给数组
st.pop();//栈顶元素出栈
}
return newList;
}
}
方法二:递归
所谓递归的思想,就是函数在自己里面不断的调用自己;
只有满足停止条件,才停止调用,否则将一直循环下去。
列如:

当递归结束时,将先执行最后生成的函数,4->3->2->1
class Solution {
ArrayList<Integer> newList = new ArrayList<Integer>();//用ArrayList来操作
public int[] reversePrint(ListNode head) {
last(head);
int[] res = new int[newList.size()];
for(int i = 0; i < res.length; i++)
res[i] = newList.get(i); //遍历ArrayList的元素
return res;
}
void last(ListNode head) {
if(head == null) return; //递归结束判断
last(head.next); //掉用自己,每调用一次,就把下一个元素推入
newList.add(head.val); //由于先执行新开的函数,所以是先推入最后的数
}
}
方法三:列表反向输入到数组中
先确定链表的长度,创建一个和长度一样长的数组。
用for循环把链表反向输入到数组中
class Solution {
public static int[] reversePrint(ListNode head) {
ListNode node = head; //创建一个“指针”,指向链表头
int length = 0;
while (node != null) //用while循环来确定数组长度
{
length++;
node = node.next;
}
int[] nums = new int[length];//创建一个和链表一样长的数组
node = head; //将“指针”归为,重新指向链表头
for (int i = length - 1; i >= 0; i--) //将链表倒放入数组
{
nums[i] = node.val;
node = node.next;
}
return nums;
}
}
本文探讨了三种方法实现从链表尾到头打印节点值:利用栈的数据结构,递归算法以及通过迭代将链表元素存入数组。适合理解链表操作和不同算法的应用。
787

被折叠的 条评论
为什么被折叠?



