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

    题目描述 在线编程

    从尾到头反过来打印出每个结点的值

    题解

    头插法可将链表反转

    /**
    *    public class ListNode {
    *        int val;
    *        ListNode next = null;
    *
    *        ListNode(int val) {
    *            this.val = val;
    *        }
    *    }
    *
    */
    import java.util.ArrayList;
    public class Solution {
        public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
           ArrayList<Integer> ret=new ArrayList<>();
           ListNode dummy=new ListNode(-1);
           ListNode cur=listNode;
            while(cur!=null){
                ListNode next=cur.next;
                cur.next=dummy.next;
                dummy.next=cur;
                
                cur=next;
            }
            cur=dummy.next;
            while(cur!=null){
               ret.add(cur.val);
                cur=cur.next;
            }
            return ret;
        }
    }
  • 相关阅读:
    CSU 1122
    CSU 1256
    CSU 1240
    HDU 1874
    CSU 1004
    Problem F CodeForces 16E
    Problem E CodeForces 237C
    Problem C FZU 1901
    12-30
    2016-12-29
  • 原文地址:https://www.cnblogs.com/zslhg903/p/11203295.html
Copyright © 2011-2022 走看看