繁体   English   中英

添加新节点将在LinkedList的开头和LinkedList的末尾添加

[英]Adding new Nodes add the beginning of LinkedList and at the end of LinkedList

公共类InsertithNode {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    LinkedList list=new LinkedList();
    list.head=new Node(2);
    list.head.next=new Node(3);


    addFront(list.head,8);

    System.out.println(list);

    addEnd(list.head,11);

    System.out.println(list);
     addEnd(list.head,15);

    System.out.println(list);

  }
public static void addFront(Node head,int value)
{
   Node newHead=new Node(value);
   newHead.next=head;
   head=newHead;

}

 public static void addEnd(Node head,int value) {

     Node newHead=new Node(value);
     Node ref=head;
     Node last=ref;

     while(ref!=null) {
         last=ref;
         ref=ref.next;
     }
     last.next=newHead;


 }

}

嗨,上面的代码是LinkedList的实现的添加头并最后添加。但是,当我运行代码时,我可以在Linked List上添加新节点作为最后一个节点,但是我无法将新节点添加到链接列表。

当我运行此代码时,输​​出为:

 head 2 --> 3 -->  null

 head 2 --> 3 --> 11 -->  null

 head 2 --> 3 --> 11 --> 15 -->  null

AddEnd方法有效,但是为什么AddFront不起作用?

在下面的调用中,您实际上是传递列表的头节点的存储位置,而不是实际的头对象:

addFront(list.head,8);

然后通过引用方法签名即节点头来保存该存储位置。

head->列表的头节点内存位置

然后,在方法的内部,您只是将引用重置为新的存储位置。

head->新节点的内存位置。

请注意:list.head是非原始对象,在Java中,非原始对象通过引用传递。

因为Node headaddFront()的局部变量,它指向list.head 当您执行head=newHead您只是在将本地变量指向刚刚创建的新Node main()的列表完全不受影响。

使用AddEnd ,您无需修改​​列表的第一个元素,因此无需发送列表。 您也不需要修改主列表,而只需修改最后一个元素,这对于该方法就足够了。

您需要将列表发送到方法,以便它可以访问其head属性。

我使用C#,而不是Java,但是我猜这应该可以工作:

    ...
    addFront(list, 8);
    ...
}

public static void addFront(LinkedList list,int value)
{
   Node newHead=new Node(value);
   newHead.next=list.head;
   list.head=newHead;
}

这里list也是一个局部变量,但是它指向主list,所以list.head是相同的内存位置,任何修改都会影响main list.head 如果您碰巧再次执行list = something ,那么它不会影响您的主列表,而只会影响您的局部变量。

顺便说一句,请尝试使用适当的变量名,以使代码不会引起混淆。 addEnd您的变量不应命名为newHead

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM