剑指Offer 06. 从尾到头打印链表 [简单]

/**
 * 自己的代码,先反转链表,再构造数组并遍历填上节点值
 * 执行用时:0 ms, 在所有 Java 提交中击败了100.00%
 * 内存消耗:38.9 MB, 在所有 Java 提交中击败了75.55%
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        ListNode sentinel = new ListNode(-1), p = head;
        int cnt = 0;
        while (p != null) {
            ListNode next = p.next;
            p.next = sentinel.next;
            sentinel.next = p;
            p = next;
            cnt++;
        }
        p = sentinel.next;
        int[] res = new int[cnt];
        for (int i = 0; i < cnt; i++, p = p.next) {
            res[i] = p.val;
        }
        return res;
    }
}
/**
  * 递归反转链表并记录长度,再构造结果数组
  * 执行用时:0 ms, 在所有 Java 提交中击败了100.00%
  * 内存消耗:39.7 MB, 在所有 Java 提交中击败了13.02%
  */
class Solution {
    public int[] reversePrint(ListNode head) {
        if (head == null) {
            return new int[0];
        }
        int[] cnt = new int[1];
        ListNode newHead = helper(head, cnt);

        int[] res = new int[cnt[0]];
        for (int i = 0; i < cnt[0]; i++, newHead = newHead.next) {
            res[i] = newHead.val;
        }
        return res;
    }
    private ListNode helper(ListNode head, int[] cnt) { // reverse list recursively, and count the nodes
        cnt[0]++;
        if (head.next == null) {
            return head;
        }
        ListNode newHead = helper(head.next, cnt);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
/**
 * 也可以不用重构反转的链表,用栈得到size和倒序的节点
 * 执行用时:1 ms, 在所有 Java 提交中击败了73.99%
 * 内存消耗:39 MB, 在所有 Java 提交中击败了63.80%
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        LinkedList<ListNode> stack = new LinkedList();
        ListNode p = head;
        while (p != null) {
            stack.push(p);
            p = p.next;
        }
        int[] res = new int[stack.size()];
        for (int i = 0; !stack.isEmpty(); i++) {
            res[i] = stack.pop().val;
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值