美文网首页
Java构造ListNode

Java构造ListNode

作者: 湯木 | 来源:发表于2020-09-10 15:36 被阅读0次
    package com.company;
    
    class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    
    class Solution {
        public static void main(String[] args) {
            Solution solution = new Solution();
            int[] input = new int[]{1, 2, 3, 4, 5};
            ListNode head = buildListNode(input);
            while (head != null) {
                System.out.println("val: " + head.val + "\tlistNode: " + head.next);
                head = head.next;
            }
        }
        /**
         * 构造ListNode
         */
        private static ListNode buildListNode(int[] input) {
            ListNode first = null, last = null, newNode;
            if (input.length > 0) {
                for (int i = 0; i < input.length; i++) {
                    newNode = new ListNode(input[i]);
                    newNode.next = null;
                    if (first == null) {
                        first = newNode;
                        last = newNode;
                    } else {
                        last.next = newNode;
                        last = newNode;
                    }
                }
            }
            return first;
        }
    }
    

    打印结果

    val: 1  listNode: com.company.ListNode@140e19d
    val: 2  listNode: com.company.ListNode@17327b6
    val: 3  listNode: com.company.ListNode@14ae5a5
    val: 4  listNode: com.company.ListNode@131245a
    val: 5  listNode: null
    

    相关文章

      网友评论

          本文标题:Java构造ListNode

          本文链接:https://www.haomeiwen.com/subject/eaepektx.html