Java 如何删除双链表的第一个节点
我有一个双链表的实现,我正在尝试删除给定位置的特定节点。我设法将第二个节点删除到最后一个节点,但当我尝试删除第一个节点时失败了,我想知道我的代码出了什么问题 我已经试过了,但还是不行Java 如何删除双链表的第一个节点,java,linked-list,doubly-linked-list,Java,Linked List,Doubly Linked List,我有一个双链表的实现,我正在尝试删除给定位置的特定节点。我设法将第二个节点删除到最后一个节点,但当我尝试删除第一个节点时失败了,我想知道我的代码出了什么问题 我已经试过了,但还是不行 head.next.previous = null; head = head.next; 这是我的密码 公共课堂散文{ 私有类节点{ 弦材; 国际尼拉乌斯; 国际尼拉乌亚斯; 节点前向; 节点下一步; 公共节点(字符串Matkul、int-Nilai、int-NilaiUAS){ 这个.Matkul=Matkul
head.next.previous = null;
head = head.next;
这是我的密码
公共课堂散文{
私有类节点{
弦材;
国际尼拉乌斯;
国际尼拉乌亚斯;
节点前向;
节点下一步;
公共节点(字符串Matkul、int-Nilai、int-NilaiUAS){
这个.Matkul=Matkul;
this.NilaiUts=Nilai;
this.NilaiUAS=NilaiUAS;
}
}
节点头、尾=空;
public void addNode(字符串matkul,int Nilai,int NilaiUAS){
Node newNode=新节点(matkul、Nilai、NilaiUAS);
如果(head==null){
头=尾=新节点;
head.previous=null;
tail.next=null;
}否则{
tail.next=newNode;
newNode.previous=尾部;
tail=newNode;
tail.next=null;
}
}
公共无效删除(整数位置){
如果(head==null | | n使用您的代码,如果场景以1个节点结束(head将指向此节点),并且您希望删除此节点(即head),则代码将失败,同时出现NullPointerException
del.next.previous = null;
as del.next为空
可以使用下面的代码从双链接列表中删除节点
// Function to delete a node in a Doubly Linked List.
// head_ref --> pointer to head node pointer.
// del --> data of node to be deleted.
void deleteNode(Node head_ref, Node del)
{
// Base case
if (head == null || del == null) {
return;
}
// If node to be deleted is head node
if (head == del) {
head = del.next;
}
// Change next only if node to be deleted
// is NOT the last node
if (del.next != null) {
del.next.prev = del.prev;
}
// Change prev only if node to be deleted
// is NOT the first node
if (del.prev != null) {
del.prev.next = del.next;
}
// Finally, free the memory occupied by del
return;
}
代码REF:
< P>你的代码的问题是,头不是在<代码> DeleNeNODE 函数中改变,因为它是按值传递的。请考虑下面的场景:
您正在删除位置1。头部指向节点1,因此
它存储节点1的地址。假设它是1001
现在您使用head引用和currentNode调用deleteNode
函数,因此head引用作为passby值传递给函数参数。因此,在函数参数head
中包含地址1001
现在执行删除操作,因此函数的头
将其位置更改为下一个节点。但是,类成员的头
仍指向第一个位置
为了克服这个问题,您可以再次设置头
,因为您是从deleteNode
函数返回它的。例如:
更改代码如下
public void delete(int position){
if (head == null || n <= 0)
return;
Node current = head;
int i;
for (i = 1; current != null && i < position; i++)
{
current = current.next;
}
if (current == null)
return;
head = deleteNode(head, current);
}
public void delete(内部位置){
如果(head==null | | n delete函数中的n
是什么?是否缺少一些代码?哦,很抱歉,我在带有position的参数中更改了n名称,我忘了在循环中更改它,您使用哪个函数删除head节点?delete
或deleteNode
?delete
方法仅用于给出位置节点的n和deleteNode
是要删除节点的函数。您还可以添加节点创建和删除序列吗?函数对我来说很好。嘿,Sandeep,节点对象不是作为参数传递给deleteNode的,通过引用传递吗?如果我在方法中执行类似head=head.next的操作(假设这没有失败)并且我尝试从主/外部的delete方法上下文打印“head”节点指向的值,它不会在下一个节点而不是原始的“head”中打印值吗node如果将head=head.next
放在deleteNode
方法中,当head
作为参数传递给函数时,将为该方法创建head
变量作为方法变量,它将指向下一个节点。但是实际的head
类的成员变量仍然指向同一个节点位置。因此,如果在删除节点
函数外部打印头部
,它将指向与前面相同的位置。考虑到您没有返回更改的头部
位置,并将其再次设置为头部
。
public void delete(int position){
if (head == null || n <= 0)
return;
Node current = head;
int i;
for (i = 1; current != null && i < position; i++)
{
current = current.next;
}
if (current == null)
return;
head = deleteNode(head, current);
}