我是 Java 初学者,目前正在完成 DSA 的 Udemy 课程。我正在学习链表,并正在研究分别向链表插入和删除节点的方法。
从目前为止我所学到的,我知道我们使用条件
head==null
来检查链表是否为空。
如果条件
head==null
为真,则 LinkedList 为空,否则不为空。
但是,我们是否也应该检查
tail==null
是否存在,因为即使我们创建了 head==null
,尾部也始终会引用 LinkedList 中的最后一个节点?
这是我的代码:
public class SinglyLinkedList{
public Node head;
public Node tail;
public int size;
//Create Linkedlist
public Node createLL(int num){
Node node=new Node();
node.value=num;
node.next=null;
head=node;
tail=node;
size=1;
return head;
}
//Insert Node
public void insertNode(int num,int location){
Node node=new Node();
node.value=num;
if(head==null){//Used to check if linked list is empty or not?
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++;
}
//Delete Node
public void deleteNode(int location){
if(head==null){//Used to check if linked list is empty or not?
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--;
}
}
}
空列表:
head -> null
tail -> null
单节点列表:
head -> node1
node1.next -> null
tail -> node1
多节点列表:
head -> node1
node1.next -> node2
node2.next -> null
tail -> node2
其中
->
表示“参考点”。因此无需检查头/尾是否为空。如果其中任何一个为 null,则表示列表没有节点并且为空。
Java LinkedList,检查 head == null 用于如果列表为空,则 head 是列表的起点。如果 head 为 null,则表示列表中没有元素。
检查 tail == null 可能并不那么简单,因为即使列表中有元素,列表的尾部也可能为 null。在 LinkedList 中,尾部通常指向最后一个节点,而其下一个引用为 null。所以,尾部为空并不一定意味着列表是空的,它意味着最后一个节点到目前为止还没有添加。
链表中的节点作为值和内存地址(下一个节点)对存在,正如您在上面的程序中实现的那样。对于最后一个节点,列表的末尾表示为 NULL。
我们检查头是否为 NULL,因为如果链表中下一个节点的内存地址为 NULL,则意味着已到达链表末尾。链表的尾部将始终为 NULL,因为它代表链表的末尾,并且不会有下一个节点可指向。