為了更加高效地調(diào)試LeetCode中關(guān)于ListNode的題目折晦,編寫了快速初始化ListNode的通用靜態(tài)方法晤斩,重寫ListNode的toString方法胃榕。
不多說了,直接上代碼
ListNode 類
重寫了toString方法妓柜,方便調(diào)試時(shí)能夠直接輸出
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);
}
}
編寫上述代碼的思路來源于fatezy's github