双链表中 first.next.previous 的意义何在?
what the point of first.next.previous in doubly-linked-lists?
当我试图在 java 中实现双向链表时,我在教科书中看到了一些奇怪的东西,用于删除第一个索引,如下所示:
public Link deleteFirst()
{
Link temp = first;
if(first.next == null)
last = null;
else
first.next.previous = null; //THIS IS WEIRD
first = first.next;
return temp;
}
对我来说奇怪的是这一行:
first.next.previous = null
我尝试使用如下所示的代码:
System.out.println(theList.first.next.Data);
System.out.println(theList.first.previous.Data);
System.out.println(theList.first.Data);//they are the same
System.out.println(theList.first.next.previous.Data);//they are the same
OUTPUT:
22
66
44
44
即使注释行:
,输出也是相同的
first.next.previous = null
所以我的问题是,这样做有什么意义?
我在网上的教程和我的教科书中都看到过这个!我看没用,是这样还是我错了?
假设列表中有三个元素a、b、c。基本上,您有以下指针算法:a-b-c,first->a,last->c。如果您尝试删除 a,那么您必须删除 link a-b。之后,first应该指向b。删除逻辑是:
</p>
<pre><code>temp = first;
if (first.next == null) // after deleting the first, list becomes empty
last = null;
else
{
first.next.previous = null; // remove the link a<-b, so b does not point anymore to a
first = first.next; // so a->b is dropped
}
当我试图在 java 中实现双向链表时,我在教科书中看到了一些奇怪的东西,用于删除第一个索引,如下所示:
public Link deleteFirst()
{
Link temp = first;
if(first.next == null)
last = null;
else
first.next.previous = null; //THIS IS WEIRD
first = first.next;
return temp;
}
对我来说奇怪的是这一行:
first.next.previous = null
我尝试使用如下所示的代码:
System.out.println(theList.first.next.Data);
System.out.println(theList.first.previous.Data);
System.out.println(theList.first.Data);//they are the same
System.out.println(theList.first.next.previous.Data);//they are the same
OUTPUT:
22
66
44
44
即使注释行:
,输出也是相同的 first.next.previous = null
所以我的问题是,这样做有什么意义? 我在网上的教程和我的教科书中都看到过这个!我看没用,是这样还是我错了?
假设列表中有三个元素a、b、c。基本上,您有以下指针算法:a-b-c,first->a,last->c。如果您尝试删除 a,那么您必须删除 link a-b。之后,first应该指向b。删除逻辑是:
</p>
<pre><code>temp = first;
if (first.next == null) // after deleting the first, list becomes empty
last = null;
else
{
first.next.previous = null; // remove the link a<-b, so b does not point anymore to a
first = first.next; // so a->b is dropped
}