void headInsert(Node* list, int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node -> data = data;
node -> next = list -> next;
node -> pre = list;
list -> next ->pre = node;
list -> next = node;
list -> data++;
}
注意顺序:
list -> next ->pre = node;
list -> next = node;
如果是第一次进入函数:
- 此时list -> next为list
- list -> next ->pre = list->pre ,所以list的前一项为node
- 之后才更新list -> next = node;所以list的后一项为node
如果是第n次进入函数:
- 此时list -> next为上一次进入的node,而上面的node -> next = list -> next;把上一次进入的node挤到第二项
- list -> next ->pre = (上一次的)node->pre ,也就是第二项指向第一项
- 之后才更新list -> next = node;
根据1,2步的操作,才成功将新头插进入的函数与原先函数进行连接
正确插入4个数:1,2,3,3
void headInsert(Node* list, int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node -> data = data;
node -> next = list -> next;
node -> pre = list;
list -> next ->pre = node;
list -> next = node;
printf("list -> %p\r\n",list);
printf("list->pre -> %p\r\n",list->pre);
printf("list->next -> %p\r\n",list->next);
printf("node->pre -> %p\r\n",node->pre);
printf("node->next -> %p\r\n",node->next);
printf("\r\n");
list -> data++;
}
但是如果是反过来的话:
void headInsert(Node* list, int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node -> data = data;
node -> next = list -> next;
node -> pre = list;
list -> next = node;
list -> next ->pre = node;
printf("list -> %p\r\n",list);
printf("list->pre -> %p\r\n",list->pre);
printf("list->next -> %p\r\n",list->next);
printf("node->pre -> %p\r\n",node->pre);
printf("node->next -> %p\r\n",node->next);
printf("\r\n");
list -> data++;
}
如果是第一次进入函数:
- 更新list -> next = node
- 此时list -> next = node,而node->pre = node
- 那这样的话就是node指向node了
- 然后因为初始化的时候是list->pre还是指向list,这个并没有改变所以list的上一项还是指向list
如果是第N次进入函数:
- list上一项永远指向list,node的上一项永远指向node
- 只有两条“线”成立,其他两条线是错的
错误插入: