从尾到头打印链表

从尾到头打印链表

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

1
2
3
4
5
6
7
8
9
10
/** 链表节点
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*/

分析题目

链表结构示意图

链表一种基础的数据结构,从尾到头就是反向遍历链表,通过链表头依次可访问到后继节点,即可得到链表的顺序结构的值。把结果依次存入栈中,再弹出即可得到反向链表值。

解决办法

  • Java 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.ArrayList;
import java.util.Stack;

public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arrayList = new ArrayList<>();
if(listNode == null){
return arrayList;
}
Stack<Integer> stack = new Stack<>();
while (listNode.next != null){
stack.push(listNode.val);
listNode = listNode.next;
}
stack.push(listNode.val);
while (!stack.isEmpty()){
arrayList.add(stack.pop());
}
return arrayList;
}
}
  • JavaScript 代码

JS下面代码array2的作用,也可以采用 unshift 方法代替。多用一个数组变量,空间复杂度高一点。但是比采用unshift函数时间复杂度略低。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function printListFromTailToHead(head)
{
let list = head
if(list == null){
return [];
}
let array1 = []
let array2 = []
while(list.next != null){
array1.push(list.val)
list = list.next
}
array1.push(list.val)
while(array1.length != 0){
array2.push(array1.pop())
}
return array2
}
文章作者: I年少有为
文章链接: https://lemonlife.top/2020/02/01/从尾到头打印链表/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 I年少有为