在链表末尾插入项时出现问题Java不工作



我试图在链表的末尾添加一个项目,但我得到了以下错误:

Exception in thread "main" java.lang.NullPointerException
at List.insertAtEnd(List.java:105)
at MainProgram.stringOperation(MainProgram.java:178)
at MainProgram.main(MainProgram.java:97)

class Link
{
public Object data;
public Link next;
}  

// List Class Method:insertAtEnd: insert a given item at the end of the list - 
public void insertAtEnd(Object item)
{
//Create a New Link    
Link newLink = new Link();
newLink.data = item;
newLink.next = null;

//Set _tail to point to null
_tail.next = newLink;
_tail = newLink;


//Add to  the Counter - For the Number of Elements in the Linked List
_numOfElements++;
}

主程序-方法之一

//StringOperations
public static void stringOperation(int option)
{
Scanner keyboard = new Scanner(System.in);

//Variables needed from User
int index, startPosition, endPosition;
String data;

//Instances needed to Perform Operations (1-9)
Link link;
List listOfIndexes;


//Switch Statement to Perform Operations
switch(option)
{


//Operation 3: insertAtEnd
case 3:
System.out.print("Please enter a String: ");
data = keyboard.nextLine();

stringList.insertAtEnd(data);

System.out.println("Completed Operation 3 for the String List." + "n");
break;


}
}

我想添加更多的代码,但为了让大家更好地理解,我在StackOverflow上不断出现错误。我需要确保每当我向链表中添加项目时,我的尾部都在更新,以便有一个更高效的程序。

更新版本:

private Link _head;
private Link _tail;
private int _numOfElements = 0;

/*Public Methods */

//(1) initialize: create an empty list (no items) - DONE!
public List()
{
_head = null;
_tail = null;
}

默认情况下,列表按照插入项目的方式排序:

java.util.List<String> list = new LinkedList<>();
list.add("First item");
list.add("Second item");

在分配_tail值之前,不能引用tail.next。

只需在insertAtEnd函数中使用即可:

if(_tail != null){
_tail.next = newLink;
}
_tail = newLink;

相关内容

  • 没有找到相关文章

最新更新