java - Insert a Node at the Tail of a Linked List in java
问题描述
I have my own linkedlist in eclipse and to insert a node at tail of linkedlist i have written a code -
void insertatlast( int data ) {
Node insert = new Node( data );
if( head == null) {
head = insert;
return;
}
Node temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = insert;
insert.next = null;
}
I have tried to solve this question on Hackerrank but in it return type is not void so, I put:
return temp.next ;
but it is showing runtime error:
Exception in thread "main" java.lang.NullPointerException
at Solution.insertNodeAtTail(Solution.java:61)
at Solution.main(Solution.java:84)
解决方案
在您共享的照片中,如果头部本身为空,则可能会出现空指针。您应该修改您的 while 条件以确保 temp!=null
while(temp!=null && ...)
推荐阅读
- hibernate - 带有可选@ManyToOne 的 HQL 多重右连接
- python - PyInstaller 不安装 pandas 之类的模块
- python - 卡在无法为使用 PEP 517 且无法直接安装的密码学构建轮子
- r - 对于大型闪亮应用程序,最初使用 bs_theme() 渲染页面可能会非常慢
- go - 为什么 time.Now() 和 time.Unix() 不同?
- ios - 由于对象列表很大,在 Xcode 中发布归档项目
- optaplanner - 为什么添加硬约束会产生不好的解决方案?
- rabbitmq - RabbitMQ 导出虚拟主机配置
- java - 从构造函数和方法输入数据
- javascript - 如何使用 Brain.js 或 Neuro.sj 实现 AI 以获取数字预测