Appearance
06-从尾到头打印链表
题目描述
https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
思路分析
递归解法
题目的本意是打印链表,那么我们可以递归链表的节点,直到 next 为空就停止往下递归,然后就是打印链表值。
因为题目需要检测结果值,所以需要用数组返回,我们可以在循环外面定义一个 array 变量,使用List<int>的方法可以动态插入数组值,最后在 ToArray 返回最终结果。常规解法,反向填充数组 先使用一次遍历,得出最终的数组长度。 第二次再遍历,按照数组反向填充进数组
实现代码
- 递归方法
csharp
public class Solution {
private List<int> arr = new List<int>();
private void ReversePrintInternal(ListNode head){
if(head.next != null){
ReversePrintInternal(head.next);
}
arr.Add(head.val);
}
public int[] ReversePrint(ListNode head) {
if(head == null){
return new int[0];
}
ReversePrintInternal(head);
return arr.ToArray();
}
}
优化
csharp
public class Solution {
private List<int> list;
private void dfs(ListNode head){
if(head == null){
return;
}
dfs(head.next);
list.Add(head.val);
}
public int[] ReversePrint(ListNode head) {
list = new List<int>();
dfs(head);
return list.ToArray();
}
}
- 反向数组
csharp
public class Solution {
public int[] ReversePrint(ListNode head) {
//get count
ListNode tempNode = head;
int count = 0;
while(tempNode != null){
count ++;
tempNode = tempNode.next;
}
//reverse assign to array
int[] arr = new int[count];
tempNode = head;
int index = 0;
while(tempNode != null){
arr[count - index -1] = tempNode.val;
index ++;
tempNode = tempNode.next;
}
return arr;
}
}
AlgoPress