You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

双向链表正反向遍历首尾元素缺失,求代码修正

双向链表遍历缺失节点问题修正

问题现象

预期输出:

[23  34  56  52]
[52  56  34  23]

实际输出:

[23  34  56]
[52  56  34]

正向遍历缺失最后一个节点52,反向遍历缺失第一个节点23。

问题根源

  1. 正向遍历:循环条件while(ptr->next != NULL)仅在当前节点的下一个节点存在时才打印当前节点,导致最后一个节点(其next为NULL)无法进入循环被打印。
  2. 反向遍历:循环条件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;
}

修正说明

  1. 正向遍历调整循环条件为while(ptr != NULL),确保每个节点都能被遍历并打印,包括最后一个节点。
  2. 正向遍历结束后ptr会变为NULL,因此需要重新遍历找到链表尾部节点,再开始反向遍历。
  3. 反向遍历同样调整循环条件为while(ptr != NULL),确保从尾部到头部的所有节点都被打印,包括第一个节点。

内容的提问来源于stack exchange,提问作者Shresth Gour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 00:24:25