3.23 06 从头到尾打印链表
题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
解答
解法一:借用栈
入栈: 遍历链表,将各节点值 push 入栈。(Python 使用 append() 方法,Java借助 LinkedList 的addLast()方法)。
出栈: 将各节点值 pop 出栈,存储于数组并返回。(Python 直接返回 stack 的倒序列表,Java 新建一个数组,通过 popLast() 方法将各元素存入数组,实现倒序输出)。
复杂度分析:
- 时间复杂度 O(N): 入栈和出栈共使用 O(N) 时间。
- 空间复杂度 O(N): 辅助栈 stack 和数组 ret 共使用 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) {
LinkedList<Integer> stack = new LinkedList<Integer>();
while(head != null){
stack.addLast(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
for(int i = 0;i < res.length; i++)
res[i] = stack.removeLast();
return res;
}
}
自己乱写的:
class Solution {
public int[] reversePrint(ListNode head) {
ArrayList<Integer> list = new ArrayList<>();
//if(head == null)
// return list;
Stack<Integer> stack = new Stack<>();
while(head != null){
stack.push(head.val);
head = head.next;
}//while
while(!stack.isEmpty()){
list.add(stack.pop());
}
int ret[]=new int[list.size()];
for(int i=0;i<list.size();i++){
ret[i]=(Integer)list.get(i);
}
return ret;
}
}
解法二:递归
递推阶段: 每次传入 head.next ,以 head == null(即走过链表尾部节点)为递归终止条件,此时直接返回。
回溯阶段: 层层回溯时,将当前节点值加入列表,即tmp.add(head.val)。
最终,将列表 tmp 转化为数组 res ,并返回即可。
复杂度分析:
- 时间复杂度 O(N): 遍历链表,递归 N 次。
- 空间复杂度 O(N): 系统递归需要使用 O(N) 的栈空间。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//
class Solution {
ArrayList<Integer> tmp = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
for(int i = 0; i < res.length; i++)
res[i] = tmp.get(i);
return res;
}
private void recur(ListNode head){
if(head == null)
return;
recur(head.next);
tmp.add(head.val);
}
}
知识点
- LinkedList 的addLast() https://www.runoob.com/java/java-linkedlist.html
- ArrayList https://www.runoob.com/java/java-arraylist.html
菜鸟教程中有用到:Collections 类也是一个非常有用的类,位于 java.util 包中
提供的 sort() 方法可以对字符或数字列表进行排序
实例:对字母进行排序
import java.util.ArrayList;
import java.util.Collections; // 引入 Collections 类
public class RunoobTest {
public static void main(String[] args) {
ArrayList<String> sites = new ArrayList<String>();
sites.add("Taobao");
sites.add("Wiki");
sites.add("Runoob");
sites.add("Weibo");
sites.add("Google");
Collections.sort(sites); // 字母排序
for (String i : sites) {
System.out.println(i);
}
}
}
输出:
Google
Runoob
Taobao
Weibo
Wiki