在双重链接列表中,first.next.previous的重点是什么?

时间:2015-11-27 15:34:34

标签: data-structures doubly-linked-list

当我尝试在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

所以我的问题是,那是什么意思? 我在网上和教科书的教程中看到过这个!我觉得它没用,所以这样或者我错了吗?

1 个答案:

答案 0 :(得分:0)

假设列表中有三个元素 a,b,c 。基本上,您有以下指针算法: a-b-c,first-> a,last-> c 。如果您尝试删除 a ,则必须删除链接 a-b 。之后, first 应指向 b 。删除逻辑将是:

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
}

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 }