双向链表正反向遍历首尾元素缺失,求代码修正
双向链表遍历缺失节点问题修正
问题现象
预期输出:
[23 34 56 52] [52 56 34 23]
实际输出:
[23 34 56] [52 56 34]
正向遍历缺失最后一个节点52,反向遍历缺失第一个节点23。
问题根源
- 正向遍历:循环条件
while(ptr->next != NULL)仅在当前节点的下一个节点存在时才打印当前节点,导致最后一个节点(其next为NULL)无法进入循环被打印。 - 反向遍历:循环条件
while(ptr->prev != NULL)仅在当前节点的前一个节点存在时才打印当前节点,导致第一个节点(其prev为NULL)无法进入循环被打印。
修正后的完整代码
#include<stdio.h> #include<stdlib.h> struct Node{ int data; struct Node* prev; struct Node* next; }; void linkedListTraversal(struct Node* head){ struct Node* ptr = head; printf("[ "); // 正向遍历:覆盖所有节点,直到ptr为NULL while(ptr != NULL){ printf("%d ",ptr->data); ptr = ptr->next; } printf("]\n"); // 重新定位到链表尾部 ptr = head; while(ptr != NULL && ptr->next != NULL){ ptr = ptr->next; } printf("[ "); // 反向遍历:覆盖所有节点,直到ptr为NULL while(ptr != NULL){ printf("%d ",ptr->data); ptr = ptr->prev; } printf("]"); } int main(){ struct Node* head; struct Node* second; struct Node* third; struct Node* fourth; head = (struct Node*) malloc(sizeof(struct Node)); second= (struct Node*) malloc(sizeof(struct Node)); third = (struct Node*) malloc(sizeof(struct Node)); fourth = (struct Node*) malloc(sizeof(struct Node)); head->data = 23; head->prev = NULL; head->next = second; second->data = 34; second->prev = head; second->next = third; third->data = 56; third->prev = second; third->next = fourth; fourth->data = 52; fourth->prev = third; fourth->next = NULL; linkedListTraversal(head); return 0; }
修正说明
- 正向遍历调整循环条件为
while(ptr != NULL),确保每个节点都能被遍历并打印,包括最后一个节点。 - 正向遍历结束后
ptr会变为NULL,因此需要重新遍历找到链表尾部节点,再开始反向遍历。 - 反向遍历同样调整循环条件为
while(ptr != NULL),确保从尾部到头部的所有节点都被打印,包括第一个节点。
内容的提问来源于stack exchange,提问作者Shresth Gour
相关产品推荐
相关产品推荐

