输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

- 方法1
计算链表的长度,反向填充数组
/**
1. Definition for singly-linked list.
2. public class ListNode {
3. int val;
4. ListNode next;
5. ListNode(int x) { val = x; }
6. }
*/
class Solution {
public int[] reversePrint(ListNode head) {
ListNode n=head;
int num=0;
while(n!=null){
num++;
n=n.next;
}
int[] a=new int[num];
n=head;
for(int i=num-1;i>-1;i--){
a[i]=n.val;
n=n.next;
}
return a;
}
}
2、堆栈
保存指针
/**
* 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> stack=new Stack<ListNode>();
ListNode n=head;
while(n!=null){
stack.push(n);
n=n.next;
}
int size=stack.size();
int[] a=new int[size];
for(int i=0; i<size;i++){
a[i]=stack.pop().val;
}
return a;
}
}
保存数字
/**
* 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<Integer> stack=new Stack<Integer>();
ListNode n=head;
int c=0;
while(n!=null){
stack.push(n.val);
n=n.next;
c++;
}
int[] a=new int[c];
for(int i=0; i<c;i++){
a[i]=stack.pop();
}
return a;
}
}
3、递归
递归和堆栈方法基本都能互换着写
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> t=new ArrayList<>();
// ArrayList<Integer> t=new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
dg(head);
int size=t.size();
int[] a=new int[size];
for(int i=0;i<size;i++){
a[i]=t.get(i);
}
return a;
}
void xunhuan(ListNode head){
if (head==null) return;
dg(head.next);
t.add(head.val);
}
}
这篇博客介绍了三种不同的方法来实现从尾到头打印链表节点值:1) 计算链表长度并反向填充数组;2) 使用堆栈保存指针;3) 递归实现。每种方法都通过实例代码详细阐述了其工作原理。
872

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



