我是靠谱客的博主 羞涩荔枝,这篇文章主要介绍LinkedList -003-从尾到头打印链表,现在分享给大家,希望可以做个参考。

题目

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

思路

读取链表是从头到尾 而打印是从尾到头
可以用Arraylist 的add 方法
add(index,val)
是在指定位置添加 然后其他数据后移

代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> list = new ArrayList<>(); ListNode tmp = listNode; while(tmp!=null){ list.add(0,tmp.val); tmp=tmp.next; } return list; } }

第二种解法 leetcode

剑指offer 06 返回数组
反转列表然后存入数组
有点点麻烦 但耗时短…

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution { public int[] reversePrint(ListNode head) { ListNode pre = null; ListNode next; ListNode cur = head; int len=0; //反转链表 while(cur != null){ len++; next = cur.next; cur.next = pre; pre = cur; cur = next; } int[] num = new int[len]; for(int i = 0; i < len; i++){ //注意在结束循环的时候cur已经指向空了 此时pre指向的是反转之后的头节点 num[i] =pre.val; pre = pre.next; } return num; } }

最后

以上就是羞涩荔枝最近收集整理的关于LinkedList -003-从尾到头打印链表的全部内容,更多相关LinkedList内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部