Java ListNode 递归 遍历


ListNode 基本结构

 

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

递归遍历到List

    private void pbulic(ArrayList<Integer> list,ListNode listNode) {
        if (listNode == null) {
            return;
        }
//     list.add(listNode.val);//从头开始遍历 pbulic(list,listNode.next); list.add(listNode.val);//从尾部开始遍历 }

从头遍历 到List

ArrayList<Integer> list = new ArrayList<Integer>();
        ArrayList<Integer> listInv = new ArrayList<Integer>();

        ListNode now = listNode;
        while (now != null) {
            list.add(now.val);
            now = now.next;
        }

        for (int i = list.size() - 1; i > -1; i--) {
            listInv.add(list.get(i));
        }
        log.info(listInv);
        now = listNode;
        while (now != null) {
            log.info(now.val);
            now = now.next;
        }
        return listInv;

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM