剑指offer - 面试题5:从尾到头打印链表

来源:互联网 发布:ubuntu文本输入 编辑:程序博客网 时间:2024/06/06 14:21

问题导读:

在不改变链表的结构的情况下,从尾到头打印链表

注:Java 实现

代码:

public class link {    //指针节点    public static class ListNode {        public Object data;        public ListNode next;    }    public static void printListReverse(ListNode pHead) {        /*         * 1.本解法是‘递归’算法         * 2.也可以使用栈,先将节点入栈,再一个一个返回         */        if(pHead != null) {            if(pHead.next != null) {                printListReverse(pHead.next);            }             System.out.print(pHead.data + " ");        }    }    public static void main(String []args) {        //创建链表        int []arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};        ListNode pHead = new ListNode();        pHead.next = null;        ListNode pNode = pHead;        for(int i = 0; i<arr.length; i++) {            ListNode pNew = new ListNode();            pNew.data = arr[i];            pNew.next = null;            pNode.next = pNew;            pNode = pNode.next;        }        //从尾到头输出链表        printListReverse(pHead.next);    }}


0 0
原创粉丝点击