五.从尾到头打印链表

来源:互联网 发布:管碧玲 知乎 编辑:程序博客网 时间:2024/05/17 23:51

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

模仿C语言版本:

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {        ArrayList<Integer> array = new ArrayList<Integer>();        ListNode pre=null;        ListNode next=null;        while (listNode != null) {            next = listNode.next;            listNode.next = pre;            pre = listNode;            listNode = next;        }//实现调转指针next        while (pre != null) {            array.add(pre.val);            pre = pre.next;        }        return array;    }

19ms
利用栈的先进后出特性。
栈版本:

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {        ArrayList<Integer> temp = new ArrayList<Integer>();        Stack<Integer> stack = new Stack<>();        while (listNode != null) {            stack.push(listNode.val);            listNode = listNode.next;        }        while (!stack.isEmpty()) {            temp.add(stack.pop());        }        return temp;    }

18ms

最后一个是递归版本,这里的递归其实也是栈原理实现的,将每一条 temp.add(stack.pop()); 压栈,当listNode为空时,开始将 temp.add(stack.pop());语句弹出栈。实现将var 值后插到Arraylist里面。

ArrayList<Integer> arrayList=new ArrayList<Integer>();    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {        if (listNode != null) {            this.printListFromTailToHead(listNode.next);            arrayList.add(listNode.val);        }        return arrayList;    }

18ms
最后一个头插法:

public ArrayList<Integer>printListFromTailToHead(ListNode listNode) {        ArrayList<Integer> list = new ArrayList<Integer>();        if(listNode == null)           return list;        while(listNode.next != null){        list.add(0,listNode.val);        listNode = listNode.next;        }        list.add(0,listNode.val);        return list; }

23ms

四个方法里面,最不好的方法就是第四种头插法。因为arralist每次插入到0位置时,会便利这个list,将所有的元素依次向后移动一个位置。而且测试证明第四个方法的时间最长为23ms.