C 双链表指针混淆

C 双链表指针混淆,c,pointers,linked-list,C,Pointers,Linked List,下面是在双链接列表中插入节点的代码 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

下面是在双链接列表中插入节点的代码

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;
        }
    }
}
struct-dllist
{
int数据;
结构dllist*prev,*next;
};
无效DLLInsert(结构dllist**head、int位置、int数据)
{
int k=1;
结构dllist*temp,*newNode;
newNode=(struct dllist*)malloc(sizeof(struct dllist));
如果(!newNode)
{
printf(“内存错误\n”);
}
新建节点->数据=数据;
如果(位置==1)
{
新建节点->下一步=*头部;
newNode->prev=NULL;
*头=新节点;
返回;
}
其他的
{
温度=*水头;
while(temp->next!=NULL&&k<位置-1)
{
k++;
温度=温度->下一步;
}
如果(临时->下一步==NULL)
{
temp->next=newNode;
newNode->prev=temp;
newNode->next=NULL;
}
其他的
{
newNode->prev=temp;
新建节点->下一步=临时->下一步;
temp->next=newNode;
temp->next->prev=newNode;
}
}
}
作为一名新手,我对底层指针操作感到有些困惑。将**头传递给函数以对其进行修改。但在位置>1的情况下,与位置=1的情况相比,使用*head(temp)的副本修改列表。谁能解释一下为什么会这样


感谢

当位置>1时,temp被设置为
*head
,代码通过链表迭代
temp
,到达索引
位置的节点。实际上,您正在修改索引
位置的节点


当position=1时,您正在修改head节点,因此不需要迭代。

position==1的情况下,新元素将成为新head。你已经知道它在哪里了。否则,您需要找到位置

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

您分配给
temp
的第一个元素是
head
,但在每次迭代中都会被下一个元素替换。

在一种情况下,您只需修改
*head
指向的内容。另一方面,您需要修改指针本身。(用方框和箭头在纸上画出这两个箱子,你就会明白原因。)@irrelephant谢谢你的解释。实际上,这意味着我可以通过将*head传递给函数来修改struct元素(即data、next和prev),但要修改*head本身,我需要传递**head。我说的对吗?是的,但我不明白这和这个关于链表的问题有什么关系。要使用
DLLInsert()
您将始终将
struct dlllist**
作为
head
传递。
    temp = temp->next;