c++ - 双向链表插入方法实现-搜索什么节点

标签 c++ data-structures linked-list

我正在复习数据结构并使用 this book .插入节点时,必须遍历列表。但是在实现双向链表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!=position将是 true是什么时候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 ;

关于c++ - 双向链表插入方法实现-搜索什么节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918047/

相关文章:

c++ - 未解析的外部符号 _D3D10CreateDeviceAndSwapChain@32 在函数“public : bool 中引用

C++ Win32 : Calling WM_PAINT from another thread using SendMessage, 绘图无效

不同内存位置中的 C++ 默认数组值

c++ - 链表C++中的内存地址

c++ - float 到双重误解???克++

data-structures - 链式哈希集的负载因子

c++ - 动态内存分配中使用的堆和数据结构有什么关系?

c++ - 在二叉搜索树中搜索对象

C:节点移除

c++ - 添加新节点后链表头始终为空