刷LeetCode题目时,有时候可能会在本地机器上测试代码有没有bug,比如在刷链表的题目时,我们需要自己生成一个链表,或者打印链表。今天把这些功能抽取了出来,写了一个ListUtil类,方便在本地测试。主要的方法是根据数组生成一个链表,或者生成随机链表(大小,链表元素的上下值都可以指定)打印一个链表。
下面看代码:
import java.security.SecureRandom; public class ListUtil { // 不容许生成实例 private ListUtil() {}; /** * 根据数组生成一个单向链表,返回头结点 * @param nums * @return */ public static ListNode creatListByArray(int... nums) { if (nums == null || nums.length == 0) { return null; } ListNode head = new ListNode(nums[0]); ListNode cur = head; for (int i = 1; i < nums.length; ++i) { cur.next = new ListNode(nums[i]); cur = cur.next; } return head; } /** * 生成一个随机数组,大小为size,随机值的下限为lowBoundInclusive(包含),上限为upBoundExclusive(不包含) * @param size * @param lowBoundInclusive * @param upBoundExclusive * @return */ private static int[] getRandomArray(int size, int lowBoundInclusive, int upBoundExclusive) { if (size <= 0) { throw new RuntimeException("size 不能为负数"); } if (upBoundExclusive <= lowBoundInclusive) { throw new RuntimeException("输入upBound与lowBound不合法,upBound必须必lowBound大"); } int[] nums = new int[size]; SecureRandom random = new SecureRandom(); int span = upBoundExclusive - lowBoundInclusive; for (int i = 0; i < size; i++) { nums[i] = random.nextInt(span) + lowBoundInclusive; } return nums; } private static int DEFAULT_ARRAY_SIZE = 10; private static int DEFAULT_LOWBOUND = 0; private static int DEFAULT_UPBOUND = 11; private static int[] getRandomArray(int size, int upBoundExclusive) { return getRandomArray(size, DEFAULT_LOWBOUND, upBoundExclusive); } private static int[] getRandomArray(int size) { return getRandomArray(size, DEFAULT_LOWBOUND, DEFAULT_UPBOUND); } private static int[] getRandomArray() { return getRandomArray(DEFAULT_ARRAY_SIZE, DEFAULT_LOWBOUND, DEFAULT_UPBOUND); } private static int[] DEFAULT_ARRAY = {1,2,3,4,5,6,7,8,9,10}; public static ListNode DEFAULT_LIST = creatListByArray(DEFAULT_ARRAY); public static ListNode getRandomList(int size, int lowBoundInclusive, int upBoundExclusive) { return creatListByArray(getRandomArray(size,lowBoundInclusive, upBoundExclusive)); } public static ListNode getRandomList(int size, int upBoundExclusive) { return creatListByArray(getRandomArray(size, upBoundExclusive)); } public static ListNode getRandomList(int size) { return creatListByArray(getRandomArray(size)); } public static ListNode getRandomList() { return creatListByArray(getRandomArray()); } public static String toString(ListNode head) { if (head == null) { return "[ ]"; } StringBuilder sb = new StringBuilder(); sb.append("[ "); while (head.next != null) { sb.append(head.val); sb.append(" -> "); head = head.next; } sb.append(head.val); sb.append(" ]"); return sb.toString(); } }