公共(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/