為了更加高效地調(diào)試LeetCode中關(guān)于ListNode的題目,編寫(xiě)了快速初始化ListNode的通用靜態(tài)方法,重寫(xiě)ListNode的toString方法。
不多說(shuō)了,直接上代碼
ListNode 類(lèi)
重寫(xiě)了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 類(lèi)
編寫(xiě)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);
}
}
編寫(xiě)上述代碼的思路來(lái)源于fatezy's github