从尾到头打印链表
从尾到头打印链表
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tab=answerKey
leetcod返回是数组
class Solution { public int[] reversePrint(ListNode head) { if(head == null) return new int[]{}; ArrayList<Integer> list = new ArrayList<>(); while(head != null){ list.add(head.val); head = head.next; } int[] nums = new int[list.size()]; int index = 0; for(int i = list.size()-1; i >= 0; i--){ nums[index++] = list.get(i); } return nums; } }
牛客 直接使用递归
public class Solution { ArrayList<Integer> list = new ArrayList<>(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if(listNode != null){ printListFromTailToHead(listNode.next); list.add(listNode.val); } return list; } }
不使用递归
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */ 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; } }
剑指offer 文章被收录于专栏
为刷过的每一道题都书写一篇题解,便于重复练习~