Java 关于链表删除的困惑

Java 关于链表删除的困惑,java,Java,我正在尝试在中实现删除功能 public static boolean delete(Object d, ListElement head){ ListElement p=find(d,head); if(p.data==null){return false;} else { System.out.println("Delete Successfully!"); if(head.data==d){head=head.next;} else{ while(head.

我正在尝试在中实现删除功能

public static boolean delete(Object d, ListElement head){
ListElement p=find(d,head);
if(p.data==null){return false;}
else {
    System.out.println("Delete Successfully!");
    if(head.data==d){head=head.next;}
    else{
    while(head.next.data!=d){
        head=head.next;
    }
    head.next=head.next.next;}
    return true;}

}
此函数主要检查元素d是否在列表中, -如果不是->返回false

-否则检查元素是否为列表的第一个元素,如果为true,则将头更改为下一个

-否则遍历到它前面的列表元素

问题是要删除的元素是第一个元素,例如布尔值s=ListElement.delete1,d;我不能使用head=head.next;为头部指定新值。但是java是通过引用传递的,为什么我不能更改它呢

//实际上,我发现我的问题是我们是否可以更改传递给函数内部函数的引用 比如:


//那么b会被更改吗?

对第一个列表元素的引用要么由列表对象本身持有,要么由一个不可见的根元素持有(如果是单链表)

void delete(visit_ptr_node_type this_is_the_node)
{
  visit_ptr_node_type one_back;
  if(anchor == NULL)
    printf("\n The list is empty");
  else
    {
    if(this_is_the_node==anchor)
      anchor=anchor->next_ptr;
    else
      {
      one_back=anchor;
      while(one_back->next_ptr != this_is_the_node)
    one_back=one_back->next_ptr;
      one_back->next_ptr = (this_is_the_node) ->next_ptr;
      }
    free(this_is_the_node);
    }
}
因此,您必须将整个列表传递给该方法,或者,如果您有不可见的根,则将根作为head传递

public static boolean delete(Object d, MyLinkedList<ListElement> list) {

  ListElement head = list.getHead();
  if (head.data.equals(d)) {   // <- ALWAYS use equals, never == to compare objects!!
    list.setHead(head.next);
  } else {
    ListElement element = head.next;

    // ... the rest is similiar to your algorithm

  } 
}

Java按引用传递的思想意味着,当您调用一个方法并将某个对象作为参数时,您将得到一个指向同一对象的新引用


更改值将更改对象,反过来也会影响其他引用。但是,如果您为参数指定一个新值,则只会更改该值,以指向不同的对象。值得一提的是,有些语言确实允许更改参数,以更改第一个传递的参数。

这不是java,而是2使用了一些全局变量锚定,因此答案并不能真正帮助解决java中的底层按引用传递问题。这是一个解决方案。嗯,我试图避免使用集合来实现我自己的类。基本上,我的问题是我们是否可以更改传递给函数内部函数的引用值。我们不能更改通过引用传递,这是最基本的。而且,我的解决方案不需要使用Collections类。我将更改字体名称以使其更清晰:Thx!所以我需要在MyLinedList类中添加setHead函数来重置head。只是想知道是否有一种更漂亮的方式将两个案例第一个元素组合在一起。非常感谢你的回复
public static boolean delete(Object d, MyLinkedList<ListElement> list) {

  ListElement head = list.getHead();
  if (head.data.equals(d)) {   // <- ALWAYS use equals, never == to compare objects!!
    list.setHead(head.next);
  } else {
    ListElement element = head.next;

    // ... the rest is similiar to your algorithm

  } 
}