亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

list(LinkedList).head 和 Node head 的區別?

list(LinkedList).head 和 Node head 的區別?

智慧大石 2023-04-26 17:03:20
我試圖使用 Node head 刪除鏈接列表的第一個節點,但是當我使用 list.head 時它不起作用?import java.util.*;    // Java program to implement     // a Singly Linked List     public class LinkedList {         Node head;     // head of list         // Linked list Node.         // This inner class is made static         // so that main() can access it         static class Node {             int data;             Node next;             // Constructor             Node(int d)             {                 data = d;                 next = null;             }         }          static void delete(LinkedList list,int x){            Node curr=list.head,prev=list.head;            if(curr.data==x&&curr!=null){                list.head=curr.next;                return ;            }            while(curr.data!=x&&curr.next!=null){                prev=curr;                curr=curr.next;            }            if(curr.data==x)                prev.next=curr.next;            return ;        }            // There is method 'insert' to insert a new node         // Driver code         public static void main(String[] args)         {             /* Start with the empty list. */            LinkedList list = new LinkedList();             list = insert(list, 1);             list = insert(list, 2);             list = insert(list, 3);                    list = insert(list, 4);                    delete(list,1);                    printList(list);                    //There is method to print list        }     }     //Output : 2 3 4當我使用上面的代碼時,我可以刪除第一個節點,但是當我使用這段代碼時,它不起作用import java.util.*;// Java program to implement // a Singly Linked List public class LinkedList {     Node head; // head of list     // Linked list Node.     // This inner class is made static     // so that main() can access it 我想知道這些是相同的東西是不同的,Node head 和 list(LinkedList).head注意:這兩種方法都適用于其他節點,區別僅適用于第一個節點。
查看完整描述

1 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

在第一個中,您將列表作為輸入傳遞,在第二個中,您將引用您的頭節點,如果您在第一個示例中注意到,如果數據存在于第一個節點,您正在修改列表的頭。這是執行此操作的代碼片段。


 Node curr=list.head,prev=list.head;

            if(curr.data==x&&curr!=null){

                list.head=curr.next;

                return ;

            }

但是在您的第二個示例中,如果在第一個節點找到數據,那么您將分配curr.next給方法本地的 head 變量,因此列表的 head 值保持不變,當您再次嘗試在 main 方法中打印列表時,它顯示舊的 head。這是第二個示例的代碼片段


Node curr=head,prev=head;

        if(curr.data==x&&curr!=null){

           head=curr.next;

            return ;

        }

因此,如果您將頭指針存儲在 LinkedList 對象中,那么您必須修改其中的值。


查看完整回答
反對 回復 2023-04-26
  • 1 回答
  • 0 關注
  • 206 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號