算法--倒序打印链表--java

来源:互联网 发布:大数据思维 编辑:程序博客网 时间:2024/06/07 03:40

使用栈来实现

static class Node{        int data;        Node next;        public Node(int data, Node next) {            this.data = data;            this.next = next;        }        @Override        public String toString() {            return "Node{" + "data=" + data + '}';        }    }    public static void main(String[] args) {        Node node3 = new Node(3, null);        Node node2 = new Node(2, node3);        Node node1 = new Node(1, node2);        print(node1);    }    private static void print(Node node) {        Node head = new Node(0, node);        Stack<Node> stack = new Stack<>();        while(head.next != null){            stack.push(head.next);            head = head.next;        }        while(!stack.isEmpty()){            System.out.println(stack.pop());        }    }

使用递归来实现

    static class Node{        int data;        Node next;        public Node(int data, Node next) {            this.data = data;            this.next = next;        }        @Override        public String toString() {            return "Node{" + "data=" + data + '}';        }    }    public static void main(String[] args) {        Node node3 = new Node(3, null);        Node node2 = new Node(2, node3);        Node node1 = new Node(1, node2);        print(node1);    }    private static void print(Node node) {        if(node == null){            return ;        }        if(node.next != null){            print(node.next);        }        System.out.println(node);    }
0 0
原创粉丝点击