我正在复习数据结构并使用 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/