C++双向链表printBackward()函数无法打印全部元素的问题排查
问题原因
你的代码中appendTail函数存在逻辑漏洞:当向空链表添加第一个节点时,仅设置了head指针,未同步设置tail指针,导致后续节点的前驱链接断裂。
具体流程:
- 添加第一个节点1时,进入
if (*head_ref == NULL)分支,设置head指向节点1后直接return,此时tail仍为初始的NULL。 - 添加第二个节点2时,
new_node->prev被赋值为NULL(因为tail还是NULL),且由于tail为NULL,无法执行(*tail_ref)->next = new_node,导致节点1的next始终为NULL,节点2的prev也为NULL。 - 添加第三个节点3时,节点3的
prev指向节点2,节点2的next指向节点3,但节点1和节点2之间没有双向链接,反向遍历时从节点3到节点2后,节点2的prev是NULL,遍历终止,因此无法输出节点1。
修复方案
修改appendTail函数,在空链表初始化分支中同时设置head和tail指针:
void appendTail(Node** head_ref,Node** tail_ref , int new_data) { // 1. allocate node Node* new_node = new Node(); // 2. Put in the data new_node->data = new_data; // 3. This new node is going to be // the last node, so make next of // it as NULL new_node->next = NULL; new_node->prev = *tail_ref; // 4. If the Linked List is empty, // then make the new node as head and tail if (*head_ref == NULL) { *head_ref = new_node; *tail_ref = new_node; // 新增:将tail指向第一个节点 return; } // 6. Change the next of last node if(*tail_ref != NULL){ (*tail_ref)->next = new_node; } *tail_ref = new_node; return; }
验证说明
修复后链表的双向链接会正确建立:
- 节点1:
prev=NULL,next=节点2 - 节点2:
prev=节点1,next=节点3 - 节点3:
prev=节点2,next=NULL
此时调用printBackward(tail)会从节点3开始,依次遍历节点2、节点1,输出3 2 1,符合预期。
内容的提问来源于stack exchange,提问作者SUPRAWEE HENGJEERASIT
相关产品推荐
相关产品推荐

