簡體   English   中英

如果我們檢查 head==null 為什么不在 Java 鏈表中檢查 tail==null 呢?

[英]If we check head==null why don't we check tail==null in Java linkedlist?

我是 Java 的初學者,目前正在完成有關 DSA 的 Udemy 課程。 我正在學習鏈表,並且正在研究分別在鏈表中插入和刪除節點的方法。

根據我目前所學的知識,我知道我們使用條件head==null來檢查鏈表是否為空。

如果條件head==null為真,則 LinkedList 為空,否則不為空。

但是,我們不應該檢查是否tail==null ,因為即使在我們 make head==null之后,tail 也會始終引用 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,則表示列表沒有節點並且為空。

正如您在上面的程序中實現的那樣,鏈接列表中的節點作為值存在,並且 memory 地址(用於下一個節點)對。 對於最后一個節點,列表的末尾表示為 NULL。

我們檢查頭部是否是NULL,因為如果鏈表中下一個節點的memory地址是NULL,則表示已經到達鏈表的末尾。 鏈表的尾部將始終是 NULL,因為它代表鏈表的結尾,並且沒有下一個節點可以指向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM