zoukankan      html  css  js  c++  java
  • 从尾到头打印链表

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

    输入描述:
    输入为链表的表头
    输出描述:
    输出为需要打印的“新链表”的表头
    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;
        }
  • 相关阅读:
    配置和兼容性测试的区别是什么?
    7 天内免登陆,测试要怎么去测试?
    在测试“支付网关”过程中的5个要点
    Hibernate入门与简谈
    jQuery专题
    Java反射机制专题
    Java IO流
    EL和JSTL专题
    泛型(Generic)
    Java异常处理
  • 原文地址:https://www.cnblogs.com/yingpu/p/5830348.html
Copyright © 2011-2022 走看看