You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode链表输入为数组的困惑:如何在Visual Studio中测试?

在Visual Studio中把LeetCode数组输入转为ListNode用于调试

要在VS里调试LeetCode的链表题目,你需要自己实现一个数组转链表的辅助方法,把LeetCode给出的数组格式输入转换成ListNode实例。下面是完整的实现步骤和代码示例:

1. 实现数组转链表的工具方法

这个方法会根据输入的int数组,按顺序创建链表节点并串联起来,返回链表的头节点:

public static ListNode BuildListFromArray(int[] values)
{
    if (values == null || values.Length == 0)
        return null;
    
    ListNode head = new ListNode(values[0]);
    ListNode current = head;
    
    for (int i = 1; i < values.Length; i++)
    {
        current.next = new ListNode(values[i]);
        current = current.next;
    }
    
    return head;
}

2. 编写测试入口(控制台程序示例)

在Visual Studio中创建一个控制台应用程序,把以下完整代码粘贴进去,就可以直接调试你的IsPalindrome方法:

using System;

/**
 * Definition for singly-linked list.
 */
public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int val=0, ListNode next=null) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    public bool IsPalindrome(ListNode head) {
        // 在这里实现你的回文链表判断逻辑
        // 示例框架(可替换为你的代码):
        if (head == null || head.next == null)
            return true;
        
        // 后续判断逻辑...
        return false;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 测试用例1:[1,2,2,1],预期输出true
        int[] testCase1 = {1,2,2,1};
        ListNode head1 = BuildListFromArray(testCase1);
        Solution sol = new Solution();
        bool result1 = sol.IsPalindrome(head1);
        Console.WriteLine($"Test Case 1 Output: {result1}");
        
        // 测试用例2:[1,2],预期输出false
        int[] testCase2 = {1,2};
        ListNode head2 = BuildListFromArray(testCase2);
        bool result2 = sol.IsPalindrome(head2);
        Console.WriteLine($"Test Case 2 Output: {result2}");
    }
    
    public static ListNode BuildListFromArray(int[] values)
    {
        if (values == null || values.Length == 0)
            return null;
        
        ListNode head = new ListNode(values[0]);
        ListNode current = head;
        
        for (int i = 1; i < values.Length; i++)
        {
            current.next = new ListNode(values[i]);
            current = current.next;
        }
        
        return head;
    }
}

3. 可选:添加链表打印方法

如果你想验证构建的链表是否正确,可以添加一个打印链表的辅助方法:

public static void PrintList(ListNode head)
{
    ListNode current = head;
    while (current != null)
    {
        Console.Write($"{current.val} ");
        current = current.next;
    }
    Console.WriteLine();
}

在Main方法里调用PrintList(head1);就能看到链表的节点顺序。

使用说明

  • 把你的IsPalindrome逻辑实现到对应的方法中
  • 运行控制台程序,就能看到每个测试用例的输出结果,也可以设置断点进行调试

内容的提问来源于stack exchange,提问作者ISquared

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:00:11