我试图使用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
static class Node {
int data;
Node next;
// Constructor
Node(int d)
{
data = d;
next = null;
}
}
static void delete(Node head,int x){
Node curr=head,prev=head;
if(curr.data==x&&curr!=null){
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.head,1);
printList(list);
//There is method to print list
}
}
//Output: 1 2 3 4
我想知道这些相同的东西是不同的,Node head和list(LinkedList).head
注意:两种方法都适用于其他节点,不同之处仅在于第一个节点。
答案 0 :(得分:0)
在第一个示例中,您将列表作为输入传递,在第二个示例中,将引用传递到根节点,如果在第一个示例中您会注意到,如果第一个节点上存在数据,则正在修改列表的头部。这样做。
Node curr=list.head,prev=list.head;
if(curr.data==x&&curr!=null){
list.head=curr.next;
return ;
}
但是在第二个示例中,如果在第一个节点上找到了数据,那么您正在将curr.next
分配给该方法本地的head变量,因此列表的head值保持不变,并且当您尝试再次在main方法中打印列表时它显示了老头。这是第二个示例中的代码片段
Node curr=head,prev=head;
if(curr.data==x&&curr!=null){
head=curr.next;
return ;
}
因此,如果要将头指针存储在LinkedList对象中,则必须修改其中的值。