簡體   English   中英

雙鏈表指針混淆

[英]Doubly Linked List Pointer Confusion

下面是在雙向鏈表中插入節點的代碼。

struct dllist
{
    int data;
    struct dllist *prev, *next;
};


void DLLInsert(struct dllist **head, int position, int data)
{
    int k = 1;
    struct dllist *temp, *newNode;
    newNode = (struct dllist *)malloc(sizeof(struct dllist));
    if (!newNode)
    {
        printf("Memory Error\n");
    }
    newNode->data = data;
    if (position == 1)
    {
        newNode->next = *head;
        newNode->prev = NULL;
        *head = newNode;
        return;
    }
    else
    {
        temp = *head;
        while (temp->next != NULL && k < position - 1)
        {
            k++;
            temp = temp->next;
        }
        if (temp->next == NULL)
        {
            temp->next = newNode;
            newNode->prev = temp;
            newNode->next = NULL;
        }
        else
        {
            newNode->prev = temp;
            newNode->next = temp->next;
            temp->next = newNode;
            temp->next->prev = newNode;
        }
    }
}

我在底層指針操作中變得有點困惑是新手。 將**頭傳遞給函數以對其進行修改。 但是在位置> 1的情況下,與position == 1的情況相比,使用* head(temp)的副本來修改列表。 任何人都可以解釋我為什么會這樣?

謝謝

當position> 1時,temp被設置為*head ,並且代碼將temp通過鏈表迭代到索引position的節點。 實際上,您正在修改索引position的節點。

當position = 1時,您正在修改頭節點,因此您不需要迭代。

position==1的情況下,您的新元素將成為新元素。 你已經確切地知道它在哪里。 否則,您需要找到位置。

temp = *head;
        while (temp->next != NULL && k < position - 1)

這用於迭代列表,直到找到要插入的位置的元素。

    temp = temp->next;

您分配給temp的第一個元素是head ,但它會被每次迭代中的下一個元素替換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM