0%

LeetCode ListNode helper

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

不多说了,直接上代码

ListNode 类

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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初始化方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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