简体   繁体   English

双链列表插入方法实现-正在搜索哪个节点

[英]Doubly-linked list insert method implementation - what node is being search for

I'm reviewing data structures and using this book . 我正在审查数据结构并使用这本书 When inserting a node, the list has to be traversed. 插入节点时,必须遍历列表。 But in the implementation of insert operation of a doubly-linked list DS I don't understand how can k be equal to position : 但是在实现双向链表DS的插入操作时,我不了解k如何等于position

while ((k < position - 1) && temp->next!=NULL) {
    temp = temp->next;
    k++;
}


if (k!=position) {   <----------------- this will true all the time?!
    printf("Desired position does not exist\n");
}

What am I missing? 我想念什么? Or is this a typo? 还是这是错字?

Thanks in advance! 提前致谢!

Here is the full method implementation: 这是完整的方法实现:

void DLLInsert(struct DLLNode **head, int data, int position) {
    int k = 1;
    struct DLLNode *temp, *newNode;
    newNode = (struct DLLNode *) malloc(sizeof( struct DLLNode ));
    if (!newNode) {
        printf("Memory Error");
        return;
    }
    newNode->data = data;
    if (position == 1) {
        newNode->next = *head;
        newNode->prev = NULL;

        if (*head) {
            (*head)->prev = newNode;
        }
        *head = newNode;
        return;
    }

    temp = *head;
    while ((k < position - 1) && temp->next!=NULL) {
        temp = temp->next;
        k++;
    }

    if (k!=position) {
        printf("Desired position does not exist\n");
    }

    newNode->next=temp->next;
    newNode->prev=temp;

    if (temp->next) {
        temp->newNode->prev=newNode;
    }

    temp->next=newNode;
    return;
}

I think you don't miss something - k!=position will always be true at this point in the code; 我认为您不会错过任何内容k!=position在此刻将始终为真; the only chance that k!=position would be true is when position==1 , but in this case the function returns before reaching the if . k!=positiontrue的唯一机会是在position==1 ,但是在这种情况下,函数在到达if之前返回。 The check should rather be if(temp==NULL) . 检查应该是if(temp==NULL)

There are some other issues, which let me think that the author did not test (actually not even compile) the code: 还有其他一些问题,让我认为作者没有测试(实际上甚至没有编译过)代码:

temp->newNode->prev=newNode;  // will this compile? I don't think that there's a member named `newNode`.

The code will crash if *head points to NULL , but one passes a position > 1 ; 如果*head指向NULL ,但代码传递的position > 1 ,则代码将崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM