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

思路
先反转链表,并记录结点个数,创建数组,遍历反转链表,依次将值插入数组
代码
class Solution {
public int[] reversePrint(ListNode head) {
ListNode hhead = new ListNode(-1);
int n=0;
while(head!=null)
{
n+=1;
ListNode temp = head.next;
head.next=hhead.next;
hhead.next = head;
head=temp;
}
int[] arr = new int[n];
hhead=hhead.next;
int i=0;
while(hhead!=null){
arr[i++]=hhead.val;
hhead=hhead.next;
}
return arr;
}
}

这是一篇关于如何从尾到头打印单链表的博客。文章介绍了一种方法,即首先反转链表,然后遍历反转后的链表,将节点值存入数组中,从而实现从尾到头的打印。
485

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



