我試圖使用 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 對象中,那么您必須修改其中的值。
添加回答
舉報
0/150
提交
取消