Algorithm 为链表伪代码插入

Algorithm 为链表伪代码插入,algorithm,insert,linked-list,pseudocode,doubly-linked-list,Algorithm,Insert,Linked List,Pseudocode,Doubly Linked List,在算法Ed3的介绍中,我阅读了用于在linkedlist中插入元素的伪代码algo,但我不理解中间步骤 x.prev = L.head if L.head != NIL L.head.prev = x L.head = x x.prev = NIL 如果我原来的链表是HEAD--4--24,我知道步骤如下: 头部-4-24 x--4--24 头部--x--4--24 和2。对应于 x.prev = L.head 为什么我们必须在头部之前插入x if L.head != NIL

在算法Ed3的介绍中,我阅读了用于在linkedlist中插入元素的伪代码algo,但我不理解中间步骤

x.prev = L.head
if L.head != NIL
    L.head.prev = x
L.head = x
x.prev = NIL
如果我原来的链表是
HEAD--4--24
,我知道步骤如下:

  • 头部-4-24

  • x--4--24

  • 头部--x--4--24

  • 和2。对应于

    x.prev = L.head
    
    为什么我们必须在头部之前插入x

     if L.head != NIL
            L.head.prev = x
    
    ?

    smbdy可以澄清一下吗?

    提示是

    L:head:pre表示L:head所属对象的pre属性 指向

    然后,algo如下所示

        //HEAD -- 4 -- 24
    
        x.next = l.head
        if L.head != NIL
            L.head.prev = x
    
        //x -- 4 -- 24
    
        L.head = x
        x.prev = NIL
    
       //HEAD -- x -- 4 --24
    

    比如说,最初头部指向节点[Y],这意味着[Y]是当前头部。我们将插入新节点[X],它将成为列表的头节点,因此头指针将指向[X]

    这里请记住,在时间开始时(在将任何内容插入列表之前),Head将指向NiL

    现在,让我们一步一步地使用伪代码来了解发生了什么:

    我们列表的当前情况是:
    Head->[Y],[Y]。prev->NiL
    ,因为Head指向[Y],所以在我们更改Head指针之前,无论何时使用Head,您都可以将其视为[Y]。现在,当前头部节点[Y]将位于[X]之后,因此让我们设置[X]=[Y]中的下一个

    1. x.next = L.head  
    
    在第一个语句之后,我们有
    [X]。next->[Y],Head->[Y],[Y]。prev->NiL

    2. if (L.head != NIL) //At the beginning Head might be pointing to NiL, and of course NiL.prev does not exist and we do not want to access illegal location.
        3. L.head.prev = x //if head is not pointing to Nil then it is pointing to [Y],
                           //in that case [X] will be the prev node of [Y], 
                        //so after this line, have Head->[Y], [X].next->[Y], [Y].prev->[X]  
    
    在第三行之后,我们可以安全地将列表头指针设置为点[X]

    4. L.head = x    
    5. x.prev = NIL //You can write L.head.prev = NIL, as [X] is now the new head
    

    您更改了CLRS中的伪代码,这是故意的吗?第一行应该是
    x.next=L.head
    not
    x.prev=L.head