LeetCode ListNode helper

作者: tikyle | 来源:发表于2016-08-25 13:14 被阅读269次

为了更加高效地调试LeetCode中关于ListNode的题目,编写了快速初始化ListNode的通用静态方法,重写ListNode的toString方法。
不多说了,直接上代码

ListNode 类

重写了toString方法,方便调试时能够直接输出

public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int x) {
        val = x;
    }

    @Override
    public String toString() {
        String s = "";
        ListNode current = this;
        while ( current != null ) {
            s = s + " " + current.val;
            current = current.next;
        }
        return s;
    }
}

ListNodeUtil 类

编写ListNode初始化方法

public class ListNodeUtil {
    public static ListNode initList (int...vals){
        ListNode head = new ListNode(0);
        ListNode current = head;
        for(int val : vals){
            current.next = new ListNode(val);
            current = current.next;
        }
        return head.next;
    }

    @Test
    public void test() {
        ListNode l = initList(1,2,3);
        System.out.println(l);
    }
}

我的github LeetCode 刷题记录
我的博客

编写上述代码的思路来源于fatezy's github

相关文章

网友评论

    本文标题:LeetCode ListNode helper

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