Java从尾到头打印链表(栈+ArrayList)
程序员文章站
2022-03-26 16:38:59
从尾到头打印链表(简单)2020年8月9日题目来源:力扣解题暴力/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public int[] reversePrint(ListNode head) {...
从尾到头打印链表(简单)
解题
- 暴力
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/ class Solution { public int[] reversePrint(ListNode head) { //初始化长度 int len=0; //取虚假头结点 ListNode root=head; while(root!=null){ len++; root=root.next; } int[] res=new int[len]; for(int i=len-1;i>=0;i--){ res[i]=head.val; head=head.next; } return res; } }
- 栈
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/ class Solution { public int[] reversePrint(ListNode head) { //用栈存拿出来的数 Stack<Integer> st=new Stack<Integer>(); //取虚假头结点 ListNode root=head; while(root!=null){ //把数字压进栈 st.push(root.val); root=root.next; } int size=st.size(); int[] res=new int[size]; for(int i=0;i<size;i++){ res[i]=st.pop(); } return res; } }
- ArrayList
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/ class Solution { public int[] reversePrint(ListNode head) { //用ArrayList存拿出来的数 List<Integer> list=new ArrayList<Integer>(); //取虚假头结点 ListNode root=head; while(root!=null){ //把数字存入ArrayList list.add(root.val); root=root.next; } int size=list.size(); int[] res=new int[size]; for(int i=0;i<size;i++){ res[i]=list.get(size-i-1); } return res; } }
本文地址:https://blog.csdn.net/weixin_41541562/article/details/107889827
下一篇: Map接口使用介绍