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

题目:

思路:

【1】本质上,递归,辅助栈都是可以实现的方法,但是相比于递归,如果能用循环解决的话我更喜欢循环,因为递归也是需要消耗内存空间的,而且本质上其实只需要知道链表大小其实就很好做了,数据从后面往前面填充即可。

代码展示:

//时间4 ms击败4.55%
//内存42 MB击败52.97%
//借助额外辅助空间的做法
/**
 * 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<Integer> ints = new ArrayList<>();
        while (head != null){
            ints.add(0,head.val);
            head = head.next;
        }
        int[] res = new int[ints.size()];
        for (int i = 0; i < ints.size(); i++){
            res[i] = ints.get(i);
        }
        return res;
    }
}

//时间0 ms击败100%
//内存41.7 MB击败95.81%
//不借助辅助空间
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        ListNode temp = head;
        int count = 0;
        while (temp != null){
            count++;
            temp = temp.next;
        }
        int[] res = new int[count];
        temp = head;
        while (temp != null){
            res[--count] = temp.val;
            temp = temp.next;
        }
        return res;
    }
}

 

posted @ 2023-01-31 12:15  忧愁的chafry  阅读(15)  评论(0编辑  收藏  举报