剑指offer系列(4)——从尾到头打印链表

来源:互联网 发布:杨辉三角c语言程序 最 编辑:程序博客网 时间:2024/06/05 16:00

题目:输入一个链表的头结点,从尾到头反过来打印出每个节点的值。

因为我们需要使最后一个节点首先输出,但我们遍历普通链表时只能从第一个节点开始,因此这是典型的后进先出模式,因此我们可以用栈来实现,因此我们也可以用递归来实现。这里我用栈来实现:

public class LinkedFromTailToHead {    static class ListNode{     //内部节点类        private ListNode next;        private int value;        public ListNode(int i) {            // TODO Auto-generated constructor stub            this.value = i;        }        public ListNode() {            // TODO Auto-generated constructor stub        }        public ListNode getNext() {            return next;        }        public void setNext(ListNode next) {            this.next = next;        }        public int getValue() {            return value;        }        public void setValue(int value) {            this.value = value;        }        @Override        public String toString() {            return "ListNode [ value=" + value + "]";        }    }    public static void main(String[] args) {        //测试方法        //创建一个根节点        ListNode root = new ListNode();        ListNode rootTmp = root;        root.setValue(-1);        //循环创建一个链表        for (int i = 0; i < 10; i++) {            root.setNext(new ListNode(i));            root = root.getNext();        }        printFromTailToHead(rootTmp);    }    public static void printFromTailToHead(ListNode root){        if (root == null) {            throw new RuntimeException("root不能为空");        }        ArrayDeque<ListNode> stack = new ArrayDeque<ListNode>();        while (root != null) {            stack.push(root);            root = root.getNext();        }        while (!stack.isEmpty()) {            root = stack.pop();            System.out.println(root.getValue());        }    }}

输出结果为:9 8 7 6 5 4 3 2 1 0 -1。

原创粉丝点击