【剑指 offer 06】从尾到头打印链表

输入一个链表的头节点,从尾到头反过来打印每个节点的值。例如:1->2->3->4->5,打印输出成5->4->3->2->1。
public class TestMethod6 {

    public static void main(String[] args) {
        ListNode<Integer> node5 = new ListNode<Integer>(5);
        ListNode<Integer> node4 = new ListNode<Integer>(4, node5);
        ListNode<Integer> node3 = new ListNode<Integer>(3, node4);
        ListNode<Integer> node2 = new ListNode<Integer>(2, node3);
        ListNode<Integer> node1 = new ListNode<Integer>(1, node2);

        //method1(node1);
        //method2(node1);
        method3(node1);
    }

    /**
     * 递归方法实现
     * 复杂度分析:时间O(n),空间O(n)
     * 存在的问题:当链表非常长的时候,就会导致函数调用的层级很深,从而有可能导致函数调用栈溢出。
     * 鲁棒性相对于栈方法实现较差
     *
     * @param node
     */
    public static void method1(ListNode node) {
        if (node != null) {
            if (node.next != null) {
                method2(node.next);
            }
            System.out.print(node + " ");
        }
    }

    /**
     * 栈方法实现
     * 复杂度分析:时间O(n),空间O(n)
     *
     * @param node
     */
    public static void method2(ListNode node) {
        Stack<ListNode> stack = new Stack<ListNode>();
        while (node != null) {
            stack.push(node);
            node = node.next;
        }
        StringBuilder str = new StringBuilder();
        while (!stack.empty()) {
            str.append(stack.pop() + " ");
        }
        System.out.println(str.toString());
    }

    /**
     * 反转单链表,然后再打印
     * 复杂度分析:时间O(n),空间O(1)
     *
     * @param node
     */
    public static void method3(ListNode node) {
        ListNode curr = node;
        ListNode prev = null;
        while (curr != null) {
            ListNode tempNext = curr.next;
            curr.next = prev;
            prev = curr;
            curr = tempNext;
        }
        StringBuilder str = new StringBuilder();
        while (prev != null) {
            str.append(prev + " ");
            prev = prev.next;
        }
        System.out.println(str.toString());
    }


    public static class ListNode<E> {

        public E value;
        public ListNode next;

        public ListNode() {
            this(null);
        }

        public ListNode(E value) {
            this(value, null);
        }

        public ListNode(E value, ListNode next) {
            this.value = value;
            this.next = next;
        }

        @NonNull
        @Override
        public String toString() {
            return value.toString();
        }
    }
}
解题思路
  • 递归
  • 栈方法
  • 反转链表打印
复杂度分析
  • 方法一的时间复杂度:O(n),空间复杂度:O(n)
  • 方法二的时间复杂度:O(n),空间复杂度:O(n)
  • 方法三的时间复杂度:O(n),空间复杂度:O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值