10.从尾到头打印单链表

对于这种颠倒顺序的问题,

我们应该就会想到栈,后进先出。

所以,这一题要么自己使用栈,要么让系统使用栈,也就是递归。注意链表为空的情况。时间复杂度为O(n)

 

 注:不要想着先将单链表反转,然后遍历输出,这样会破坏链表的结构,不建议。

方法1:(自己新建一个栈)

// 方法:从尾到头打印单链表 (自己新建一个栈)
    public void reversePrint1(Node head) {
        if (head == null) {
            return;
        }
        Stack<Node> stack = new Stack<Node>();// 新建一个栈
        Node current = head;
        // 将链表的所有节点压栈
        while (current != null) {
            stack.push(current);
            current = current.next;
        }
        while (stack.size() > 0)// 将栈中的节点打印输出即可
        {
            System.out.println(stack.pop().data);
        }
    }

方法2:(使用系统的栈:递归,代码优雅简洁)

    // 从尾到头打印单链表(使用系统的栈:递归,代码优雅简洁)
    public void reversePrint2(Node head) {
        if (head == null) {
            return;
        }
        reversePrint2(head.next);
        System.out.println(head.data);
    }

总结:方法2是基于递归实现的,代码看起来简洁优雅,但有个问题:当链表很长的时候,

就会导致方法调用的层级很深,有可能造成栈溢出。而方法1的显式用栈,是基于循环实现的,代码的鲁棒性要更好一些。

 测试代码:

LinkList list6 = new LinkList();
		for (int i = 4; i < 7; i++) {
			list6.add(i);
		}
		System.out.print("从尾到头打印单链表:");
		System.out.print("
");
		list6.reversePrint1(list6.head);

测试结果:

从尾到头打印单链表:
6
5
4

原文地址:https://www.cnblogs.com/guweiwei/p/6861739.html