本地IDE调试LeetCode中链表相关问题

当我们想在本地的IDE调试LeetCode代码时,直接复制代码来调试肯定会出问题,链表相关的问题在LeetCode上内部封装了其节点类,所以我们在本地调试的时候,需要自己添加节点类才能正常调试。

首先看LeetCode上关于链表的题目是如何给的:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {

    }
}

LeetCode上用注释的方式给出了其节点类的定义方式,如果我们直接在IDE中从Solution开始编写代码,那么ListNode这一类型一定会报错,所以我们要在工程目录中添加一个新的文件ListNode,将注释部分复制进去

public class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
 }
 

这样Solution中的的节点对象就不会报错了。

但是想自己给测试用例这样还不够,ListNode这个类还需要添加东西,将输入的数组转换成链表

public class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }

    // 链表节点的构造函数
    // 使用arr为参数,创建一个链表,当前的ListNode为链表头节点
    public ListNode(int[] arr){
        if(arr == null || arr.length == 0)
            throw new IllengalArgumentException("arr can not be empty");

        this.val = arr[0];
        ListNode cur = this;
        for(int i = 1; i < arr.length; i ++){
            cur.next = new ListNode(arr[i]);
            cur = cur.next;
        }
    }
    
    //以当前节点为头节点的链表信息字符串 方便查看
    @Override
    public String toString(){
        StringBuilder res = new StringBuilder();
        ListNode cur = this;
        while(cur != null){
            res.append(cur.val + "->");
            cur = cur.next;
        }
        res.append("NULL");
        return res.toString();
    }
 }

整个数组转链表的方法就完成了,最后在Solution中测试可以添加一个main函数来实现


class Solution {
    public int[] reversePrint(ListNode head) {
        //需要补充的代码
    }

    public static void main(String[] args){
        
        int[] nums = {1, 2, 3, 4, 5, 6, 5, 5}
        ListNode head = new ListNode(nums);
        System.out.println(head);

        ListNode res = (new Solution()).reversePrint(head);
        System.out.println(res);
    } 
}

这样就能在IDE中很好的测试链表相关的题目了。

 

发布了80 篇原创文章 · 获赞 184 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/hesongzefairy/article/details/104681871