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
:
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; the only chance that k!=position
would be true
is when position==1
, but in this case the function returns before reaching the if
. The check should rather be 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
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.