首页 > 其他分享 >剑指pffer 06. 从尾到头打印链表

剑指pffer 06. 从尾到头打印链表

时间:2023-01-28 16:31:46浏览次数:51  
标签:head 06 val int list pffer arr 链表 ListNode

1.题目

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。


2.代码

方法一:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
//定义一个集合储存链表里的值
List<Integer> list = new ArrayList<>();
while(head!=null){
list.add(head.val);
head = head.next;
}
//把集合里的值倒着存到数组里面
int[] arr = new int[list.size()];
for(int i=0; i<list.size(); i++){
arr[i] = list.get(list.size()-1-i);
}
return arr;

}
}



方法二:递归

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
//定义一个集合,给递归的时候存进去
List<Integer> list = new ArrayList<>();
public int[] reversePrint(ListNode head) {
recur(head);//这个步骤完成之后,就把链表里的全部值都添加成功了
//再把集合的元素倒着添加进去
int[] arr = new int[list.size()];
for(int i=0; i<list.size(); i++){
arr[i] = list.get(list.size()-1-i);
}
return arr;


}
void recur(ListNode head){
if(head==null){//递归的出口
return;
}
list.add(head.val);//把当前的值添加到集合中
recur(head.next);//递归,下一个值,移动指针

}
}

标签:head,06,val,int,list,pffer,arr,链表,ListNode
From: https://blog.51cto.com/u_15806469/6024996

相关文章

  • 链表简单题
    面试题02.03.删除中间节点难度简单173收藏分享切换为英文接收动态反馈若链表中的某个节点,既不是链表头节点,也不是链表尾节点,则称其为该链表的「中间节点」。假定已知......
  • 两条链表相交节点问题
    可以分为链表是否有环来拆分问题packagedayone.tre;publicclassIntersectNode{publicstaticNodegetIntersectNode(Nodehead1,Nodehead2){i......
  • C语言实现一个简单的单向链表list
    C语言实现一个简单的单向链表listcheungmine用C语言实现一个简单实用的单向链表list,具有一定的实际意义。尤其我们不想使用STL里面的list<...>类的时候。我实现的这个list,结......
  • 06 多维数组
    多维数组这张图更好看一点......
  • 83. 删除排序链表中的重复元素
    题目描述给定一个已排序的链表的头head,删除所有重复的元素,使每个元素只出现一次。返回已排序的链表。方法1双指针方式描述指针p去找寻是否为相同的节点如果......
  • 链表和数组哪个实现队列更快
    链表->队列classQueueByLinkList{constructor(){this.queue=null}add(value){if(!this.queue){this.queue={......
  • 反转单向链表
    数组生成单向链表constcreateLinkList=(arr=[1,2,3,4,5,6])=>{constlength=arr.length;letcurNode={value:arr[arr.length-1],......
  • 【奇妙的数据结构世界】用图像和代码对链表的使用进行透彻学习 | C++
    第九章链表:::hljs-center目录第九章链表●前言●一、链表是什么?1.简要介绍2.具体情况●二、链表操作的关键代码段1.类型定义2.常用操作●总结:::......
  • [LeetCode] 1061. Lexicographically Smallest Equivalent String
    Youaregiventwostringsofthesamelength s1 and s2 andastring baseStr.Wesay s1[i] and s2[i] areequivalentcharacters.Forexample,if s1=......
  • 06-JavaSE:面向对象编程
    面向过程的思维模式面向过程的思维模式是简单的线性思维,思考问题首先陷入第一步做什么、第二步做什么的细节中。这种思维模式适合处理简单的事情,比如:上厕所。如果面对......