Skip to content

Instantly share code, notes, and snippets.

@TWiStErRob
Created November 26, 2015 19:00
Show Gist options
  • Save TWiStErRob/69136b48d688f78a9548 to your computer and use it in GitHub Desktop.
Save TWiStErRob/69136b48d688f78a9548 to your computer and use it in GitHub Desktop.
LeetCode helper methods for console debugging
static {
System.setOut(new java.io.PrintStream(new java.io.FilterOutputStream(System.out) {
int count = 10 * 1024;
@Override public void write(int b) throws IOException {
if (count > 0) {
super.write(b);
--count;
}
}
@Override public void write(byte[] b, int off, int len) throws IOException {
if (count > 0) {
len = Math.min(count, len);
super.write(b, off, len);
count -= len;
}
}
}));
}
private static String val(ListNode node) {
return node != null ? String.valueOf(node.val) : "null";
}
private static String list(ListNode head) {
return list("", head, -1);
}
private static String list(ListNode head, int k) {
return list("", head, k);
}
private static String list(String label, ListNode head) {
return list(label, head, -1);
}
private static String list(String label, ListNode head, int k) {
StringBuilder sb = new StringBuilder();
sb.append(label).append("[");
ListNode slow = head;
ListNode fast = head;
while (slow != null) {
sb.append(val(slow));
if (slow.next != null) {
sb.append(", ");
}
if (--k == 0) {
if (slow.next != null) sb.append("...");
break;
}
slow = slow.next;
fast = fast != null && fast.next != null? fast.next.next : null;
if (fast != null && slow == fast) {
slow = head;
while (slow != fast) {
sb.append(val(fast));
if (fast.next != null) {
sb.append(", ");
}
slow = slow.next;
fast = fast.next;
}
sb.append("cycle from ");
sb.append(val(slow));
break;
}
}
sb.append("]");
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment