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;
        }
  • 相关阅读:
    Python解释器相关知识
    简单了解下Flask
    Scoket编程
    __file__的作用
    jquery编写可折叠列表
    浑浑噩噩的一天
    js实现杨辉三角
    js闭包
    python读取word表格
    HTMLTestRunner报告
  • 原文地址:https://www.cnblogs.com/yingpu/p/5830348.html
Copyright © 2011-2022 走看看