面试题6: 从头到尾打印链表

2019-10-02  本文已影响0人  mark_x
package cn.zxy.interview;

/**
 * 要求从尾到头打印链表:
 * 想用递归, 在递的时候取出元素压栈, 返回的时候弹栈打印
 * 为了方便思考, 先考虑用实现数组的递归倒序打印
 * 数组分析:
 * 1. 终止条件:i == length
 */
public class A06_TraverseLinkList {
    public static void reversePrintArray(int[] a, int index){
        if (a == null || a.length == 0) return;

        if(index > a.length - 1) return;
        int num = a[index];
        index = index + 1;
        reversePrintArray(a, index);
        System.out.println(num);
    }

    // 链表一样的道理
    public static class Node{
        private int value;
        private Node next;

        public Node() {
        }

        public Node(int value, Node next) {
            this.value = value;
            this.next = next;
        }
    }

    private static void createNode(Node rootNode) {
        for (int i = 0; i < 10; i++) {
            Node node = new Node();
            node.value = i;
            node.next = rootNode.next;
            rootNode.next = node;
        }
    }

    public static void reversePrintLinkList(Node x){
        // 终止条件
        if(x == null) return;
        int value = x.value;
        reversePrintLinkList(x.next);
        System.out.println(value);
    }

    public static void main(String[] args) {
        int[] a = {1,2,3,4,5,6,7};
        reversePrintArray(a, 0);

        // 链表
        System.out.println("-------逆序链表---------");
        Node rootNode = new Node(10, null);
        createNode(rootNode);
        reversePrintLinkList(rootNode);

    }
}

上一篇 下一篇

猜你喜欢

热点阅读