Head值設置為空,但仍顯示Tail值 [英] Head value set to null but tail value still gets displayed

查看:0
本文介紹了Head值設置為空,但仍顯示Tail值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

在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

推薦答案

head成為null只是意味著您無法再到達第一個Node。這還意味著您無法通過next引用訪問整個鏈,因為您沒有起點。
垃圾收集器被允許釋放所有不能再到達的對象。在您的示例中,除tail節點外的所有節點,因為您仍在SinglyLinkedList中保留對它的引用。

所以實際上您有一種空的LinkedList,因為您不能再正確地訪問它。但是您仍然保持tail節點的活動狀態,因為您引用了它。正確的解決方案是將tail也設置為null,這樣垃圾回收器也可以釋放此節點。

這篇關于Head值設置為空,但仍顯示Tail值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!

查看全文
登錄 關閉
掃碼關注1秒登錄
發送“驗證碼”獲取 | 15天全站免登陸
全免费A级毛片免费看无码播放