如果输入ListArray为空,则返回空列表[delete]

问题描述:

如果输入ListArray为空,则试图返回空ListNode。如果输入ListArray为空,则返回空列表[delete]

的ListNode类:

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

和函数返回空Listnode当输入[]和输出应该是[]是:

public ListNode mergeKLists(ListNode[] lists) { 
    if(lists == null)  // this is not the case, because an empty list is there 
     return null; 
    if(lists.length == 0)  
     return lists[0]; //this won't work because there's nothing at the 0th index 
     return null; // won't work because I want to return an empty ListNode 
} 
+0

目前尚不清楚是什么,你的意思是“空ListNode”。您可以返回'新的Listnode(0)'或'新的ListNode()' – c0der

+0

谢谢!我从你的回答中得到了一个提示。基本上,如果我使用'新的ListNode()',那么它会返回一个错误,指出期望的整数。但'新的ListNode(0).next'工作! – Neha

+0

'new ListNode(0).next'为null,因为你没有初始化'next'。查看更多信息的答案。 – c0der

目前还不清楚你是什么意思是“空ListNode”。
您可以返回new Listnode(0)new ListNode()。 对于以后你需要定义适当的构造函数:

ListNode() { } 
+0

感谢您的回答。 – Neha

你可以这样说:

public ListNode mergeKLists(ListNode[] lists) { 
     if(lists.length == 0)  
      //This will return an ListNode array of length 0. i.e. [] 
      return new ListNode[0]; 
    } 
+0

这将返回值为0的ListNode。事实并非如此。节点应该没有价值。 – Neha

+0

你甚至尝试过运行它吗? –