剑指 Offer 06. 从尾到头打印链表
38
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000`
这题我第一次看有点懵,看了很久还是有点懵。。。。。
之后看了解答,大致的思路是:
1.首先要认识到链表只能从前至后依次访问每个节点,不同与数组可以随便得到某个位置的元素;
2.很多时候,我们都知道栈的特点是“先进后出”,但却不知道怎么用,那么这道题就是一个很好的例子了,从尾到头反过来返回每个节点的值,我们便可以利用栈的特点,先讲链表的各个节点压栈,然后出栈,就ojbk了
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;
}
}
作者:jyd
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/mian-shi-ti-06-cong-wei-dao-tou-da-yin-lian-biao-d/
```java
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
while (temp != null) {
stack.push(temp);
temp = temp.next;
}
int size = stack.size();
int[] print = new int[size];
for (int i = 0; i < size; i++) {
print[i] = stack.pop().val;
}
return print;
}
}
class Solution {
public int[] reversePrint(ListNode head) {
int number = 0;
ListNode temp = head;
while(temp!=null){
number++;
temp = temp.next;
}
int[] num = new int[number];
ListNode temp1 = head;
int var = number-1;
for(int i = var; i >= 0; i--){
num[i] = temp1.val;
temp1 = temp1.next;
}
return num;
}
}
对ListNode的解释,一个类型为ListNode的节点,有类型为int的val,也有类型为ListNode的next,最后的一种方法是用了该链表的特性而写出来的,当链表的某个节点为null时,说明该节点为该链表的最后一个节点,以此求出链表有多少个节点,之后是倒序排列,比较简单
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/mian-shi-ti-06-cong-wei-dao-tou-da-yin-lian-biao-b/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)