簡體   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