Head值设置为空,但仍显示Tail值
it1352
帮助1人
问题说明
在Java链表中,如果head=空,则LinkedList为空。但是,当我设置HEAD=NULL并打印Tail的值时,将显示该值。为什么我们说head==NULL表示LinkedList为空?为什么在链表应该为空的情况下显示尾部值?我们是否也应该检查id(Tail==NULL)?
public class SinglyLinkedList{
public Node head;
public Node tail;
public int size;
public Node createLL(int num){
Node node=new Node();
node.value=num;
node.next=null;
head=node;
tail=node;
size=1;
return head;
}
public void insertNode(int num,int location){
Node node=new Node();
node.value=num;
if(head==null){//Check
createLL(num);
return;
}
else if(location==0){
node.next=head;
head=node;
}
else if(location>=size){
node.next=null;
tail.next=node;
tail=node;
}
else{
Node tempNode=head;
int index=0;
while(index<location-1){
tempNode=tempNode.next;
index ;
}
node.next=tempNode.next;
tempNode.next=node;
}
size ;
}
public void traverse(){
if(head==null){//Check
System.out.println("The linked list is empty");
}
Node tempNode=head;
for(int i=0;i<size;i ){
System.out.print(tempNode.value);
if(i!=size-1){
System.out.print("->");
}
tempNode=tempNode.next;
}
System.out.println();
}
public void deleteNode(int location){
if(head==null){//Check
System.out.println("The linked list is not present");
return;
}
else if(location==0){
head=head.next;
size--;
if(size==0){
tail=null;
}
}
else if(location>=size){
Node tempNode=head;
for(int i=0;i<size-1;i ){
tempNode=tempNode.next;
}
if(head==null){
tail=null;
size--;
return;
}
tempNode.next=null;
tail=tempNode;
size--;
}
else{
Node tempNode=head;
int index=0;
while(index<location-1){
tempNode=tempNode.next;
index ;
}
tempNode.next=tempNode.next.next;
size--;
}
}
主类
class Main {
public static void main(String[] args) {
SinglyLinkedList sLL=new SinglyLinkedList();
sLL.createLL(5);
sLL.insertNode(15, 1);
sLL.insertNode(20, 2);
sLL.insertNode(39, 3);
sLL.insertNode(45, 4);
sLL.traverse();
sLL.head=null;
System.out.println(sLL.tail.value);
}
}
输出: 5-15-20-39-45
45
正确答案
#1
head
成为null
只是意味着您无法再到达第一个Node
。这还意味着您无法通过next
引用访问整个链,因为您没有起点。
垃圾收集器被允许释放所有不能再到达的对象。在您的示例中,除tail
节点外的所有节点,因为您仍在SinglyLinkedList
中保留对它的引用。
所以实际上您有一种空的LinkedList,因为您不能再正确地访问它。但是您仍然保持tail
节点的活动状态,因为您引用了它。正确的解决方案是将tail
也设置为null
,这样垃圾回收器也可以释放此节点。
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanbh
系列文章
更多
同类精品
更多
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
复制文件夹/文件而不修改属性?
it1352 07-15