题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:0 <= 链表长度 <= 10000
思路1
先进行链表反转,再将反转后的链表转换成数组输出。
链表反转共有4种方法:分别是头插法(新建一个链表),原地修改链表(互换相邻两个节点指向),递归法,利用栈解决。(之前文章有详细介绍)
代码1
/**
* 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 newHead = reverseList(head);
ListNode node = newHead;
//获得链表的长度
int size = 0;
while(node != null){
size++;
node = node.next;
}
int[] ret = new int[size];
for(int i = 0; i < size; i++){
ret[i] = newHead.val;
newHead = newHead.next;
}
return ret;
}
public ListNode reverseList(ListNode head){
//判断边界条件
if(head == null || head.next == null){
return head;
}
ListNode prev = null;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}
思路2:更简洁:反向填充数组就完事了!
class Solution {
public int[] reversePrint(ListNode head) {
ListNode node = head;
int len = 0;
while(node!=null){
len++;
node=node.next;
}
int[] res = new int[len];
while(head!=null){
res[--len] = head.val;
head=head.next;
}
return res;
}
}
本文介绍了一种通过链表逆序打印的方法。首先通过链表反转实现,再将反转后的链表转换为数组输出;其次介绍了更为简洁的方法,即直接反向填充数组。这两种方法都适用于链表长度不超过10000的情况。
785

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



