当我尝试将节点添加到初始化为null的链接列表时,我遇到了问题。在我的方法中,我设置了一个测试用例,以检查节点是否最初为null,如果是,则创建一个具有传入值的新节点。但无论出于何种原因,它都不起作用,除非该节点至少已经传递了一个元素检查出来:
Node addNode(Node node, int val)
{
if(node == null)
{
Node newNode = new Node(val);
//node = newNode;
return newNode;
}
node.next = addNode(node.next, val);
return node;
}
//Driver Class
Scanner in = new Scanner(System.in);
Node myNode = new Node(1);
int numEntries = in.nextInt();
for(int i = 0 ; i < numEntries ; i++)
{
int inputVal = in.nextInt();
myNode.addNode(myNode, inputVal);
}
如果将myNode初始化为空值,则上述代码将不会运行(Node myNode = null;)
完整代码:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static class Node
{
private int value;
Node next;
public Node()
{
next = null;
}
public Node(int val)
{
value = val;
next = null;
}
Node addNode(Node node, int val)
{
if(node == null)
{
Node newNode = new Node(val);
//node = newNode;
return newNode;
}
node.next = addNode(node.next, val);
return node;
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
Node myNode = new Node(1);
Node current = null;
Node oddFirst = new Node(1);
int numEntries = in.nextInt();
for(int i = 0 ; i < numEntries ; i++)
{
int inputVal = in.nextInt();
myNode.addNode(myNode, inputVal);
}
current = myNode;
while(current != null) // Check if values were copied correctly
{
if(oddFirst == null)
{
oddFirst = new Node(current.value);
}
oddFirst.addNode(oddFirst,current.value);
//oddFirst = current.next;
//oddFirst = oddFirst.next;
current = current.next.next;
}
while(oddFirst != null)
{
System.out.println("Current Value: " + oddFirst.value);
oddFirst = oddFirst.next;
}
}
}
答案 0 :(得分:1)
链接列表的简单解决方案:
class Node {
int val;
Node next;
}
public class LinkedList {
public Node first;
public Node last;
public void addNext(int val) {
Node node = new Node();
node.val = val;
if(last == null) {
first = last = node;
}
else {
last.next = node;
last = node;
}
}
}
原始代码的主要问题是它不关心空列表的情况。 您无法辨别列表由单个1值和空列表组成的情况。
答案 1 :(得分:0)
因为您没有处理addNode()的返回值。
您将在以下函数中返回一个节点:
Node addNode(Node node, int val)
但你不是在这里处理回报:
myNode.addNode(myNode, inputVal);
这可以帮助您找出解决方案。