剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
思路一:
首先先确定链表的长度,再用链表长度规定数组长度,储存在数组时从数组最后一个下标往前存。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode h) {
int len = getLength(h);
int[] arr = new int[len];
for(int i=0;i<len;i++){
arr[len-1-i]=h.val;
h=h.next;
}
return arr;
}
public int getLength( ListNode h){
int lent=0;
while(h!=null){
h=h.next;
lent++;
}
return lent;
}
}
思路二:
根据先进后出的思想可以用栈来实现,(Java中栈的方法?)把链表中的每个节点依次压入栈中,然后确定栈的大小,根据栈的大小创建数组,将出栈的元素存入数组中。
注:s.push(head) 以及 s.pop().val
时间复杂度:O(n)。正向遍历一遍链表,然后从栈弹出全部节点,等于又反向遍历一遍链表。
空间复杂度:O(n)。额外使用一个栈存储链表中的每个节点。
/**
* 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> s= new Stack<ListNode>();
while(head!=null){
s.push(head);
head=head.next;
}
int a=s.size();//s.pop后size会发生变化,因此要在这里定义一个值
int[] arr = new int[a];
for(int i=0;i<a;i++){
arr[i]=s.pop().val;
}
return arr;
}
}
题解中Stack中元素类型为ListNode,可以替换为直接保存val的类型Integer
public class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
while (head != null) {
stack.push(head.val);
head = head.next;
}
int size = stack.size();
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = stack.pop();
}
return array;
}
}
思路三:
直接使用ArrayList也可以,从ArrayList中倒序取出
能用到ArrayList只要是因为它可以储存不定长的量,因为题目给定的链表长度我们不知道,所以我们可以用ArrayList得到长度,再倒序取出
什么是ArrayList
注:list.add 以及list.get
//添加元素
public boolean add(E e)
//在指定位置添加一个元素
public void add(int index, E element)
//获取元素
public E get(int index)
public class Solution {
public int[] reversePrint(ListNode head) {
ArrayList<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
int size = list.size();
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = list.get(size - i -1);
}
return array;
}
}
如果是“打印”而不是返回数组,如何在 O(1) 空间复杂度实现?
这道题的链表是可变的。我们要充分利用它的可变性,来实现 O(n)O(n) 时间复杂度和 O(1)O(1) 空间复杂度的算法。思路很简单:首先,我们把这个链表反转过来(详见反转链表),然后迭代依次打印。如果题目要求不改变链表,直接再反转回来即可。
```java
public static void printReverse(ListNode head) {
ListNode node = reverseList(head);
while (node != null) {
System.out.println(node.val);
node = node.next;
}
// reverseList(node);
}
private static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode node = head;
while (node != null) {
ListNode next = node.next;
node.next = prev;
prev = node;
node = next;
}
return prev;
}
作者:yuantj
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/ni-xu-da-yin-lian-biao-ru-guo-shi-da-yin-er-bu-shi/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。