LeetCode ListNode helper

为了更加高效地调试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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,891评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,161评论 25 708
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 大家好! 我每天都在看老师们写的简书,个个都被录用,说真的老师们确实都很有才华,都能写出自己的心声,是他们文化程度...
    笑看风云_9628阅读 168评论 0 4
  • 四点出发去奥体,出了门发现没带卡,在路上徘徊了一下,还是决定买票坐车。今天没什么人,一直投篮顺便看旁边足球场,因为...
    等风蒲公英阅读 145评论 0 0