首页 > 其他 > 详细

从尾到头打印链表

时间:2016-09-01 17:51:44      阅读:162      评论:0      收藏:0      [点我收藏+]

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

输入描述:
输入为链表的表头
输出描述:
输出为需要打印的“新链表”的表头
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        if(listNode == null) return list;
        ListNode current = listNode;
        ListNode temp = null;
        ListNode next = null;
        while(current!=null){
            next = current.next;
            current.next = temp;
            temp = current;
            current = next;
        }
        while(temp!=null){
            list.add(temp.val);
            temp = temp.next;
        }
        return list;
    }

思路2:把节点存入到栈中,输出栈中的元素即可。

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

 

从尾到头打印链表

原文:http://www.cnblogs.com/yingpu/p/5830348.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!