java - 添加新节点添加 LinkedList 的开头和末尾

标签 java linked-list

公共(public)类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 添加头和添加最后一个的实现。但是,当我运行代码时,我可以将新节点添加为链表上的最后一个节点,但无法将新节点添加到链表的乞求中列表。

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

 head 2 --> 3 -->  null

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

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

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

最佳答案

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

addFront(list.head,8);

然后通过方法签名(即节点头)的引用来保存内存位置。

head ->List的头节点内存位置

然后在方法体内,您只需将引用重置为新的内存位置。 :

head -> 新节点内存位置。

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

关于java - 添加新节点添加 LinkedList 的开头和末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46383546/

相关文章:

java - 从 CheckStyle 中的方法计数中排除 getter 和 setter

java - 实现 OnClickListener

java - 该嵌套类的实际目的是什么?

java - 在 java 中使用 '?' 参数化 LinkedList

c - double free or corruption (fasttop) 错误 c/c++ linux

java - 如何将 Java 安全层(Apache Shiro|Spring Security)集成到 webapp 菜单系统

java - 无法在调用 DatePickerDialog Show 时添加窗口异常

c++ - 双向链表按顺序插入

javascript - 单链表上的简单递归迭代 JavaScript

c - 具有动态链表的图形表示