繁体   English   中英

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

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

我正在审查数据结构并使用这本书 插入节点时,必须遍历列表。 但是在实现双向链表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");
}

我想念什么? 还是这是错字?

提前致谢!

这是完整的方法实现:

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;
}

我认为您不会错过任何内容k!=position在此刻将始终为真; k!=positiontrue的唯一机会是在position==1 ,但是在这种情况下,函数在到达if之前返回。 检查应该是if(temp==NULL)

还有其他一些问题,让我认为作者没有测试(实际上甚至没有编译过)代码:

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

如果*head指向NULL ,但代码传递的position > 1 ,则代码将崩溃。

暂无
暂无

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

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