【发布时间】:2022-01-09 21:22:05
【问题描述】:
在java中单独使用LinkedList,当我为head(head=null)为null时,如何编写使tail(tail=null)为null的代码?我是初学者,因此觉得很难。我在每个方法中都包含了 if(head==null) ,但也想实现在 head=null 时设置 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){
createLL(num);
return;
}
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){
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 boolean searchElement(int num){
Node tempNode=head;
for(int i=0;i<size;i++){
if(tempNode.value==num){
System.out.println("The value is present at index:"+i);
return true;
}
tempNode=tempNode.next;
}
System.out.println("The value is not present");
return false;
}
public void deleteNode(int location){
if(head==null){
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--;
head=tail=null;
}
else{
Node tempNode=head;
int index=0;
while(index<location-1){
tempNode=tempNode.next;
index++;
}
tempNode.next=tempNode.next.next;
size--;
}
}
public void deleteSinglyLinkedList(){
if(head==null){
System.out.println("The linkedlist is absent");
}
head=tail=null;
System.out.println("The entire linked list has been deleted");
}
}
【问题讨论】:
-
if(head == null) tail = null;或(等效):if(head == null) tail = head;;) -
我应该将此代码放在我的程序中的什么位置,以便它可以处理插入、删除、遍历和搜索等所有操作?
-
请在您的问题中添加更多详细信息!另请查看minimal reproducible example 和how-to-ask
-
我添加了我的代码。
-
就像我在对your previous question 的回答中所写的那样,您最好在您的类中添加一个负责清除的方法,而不是让主代码直接更改
head的值。
标签: java algorithm data-structures linked-list singly-linked-list