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

C++双向链表元素存在性检测问题及代码调试求助

双向链表重复元素检测与添加、遍历实现方案

问题根源

你写的if(head == displayPointer)是在比较两个指针的内存地址,而你刚把displayPointer = head赋值,所以这两个指针必然指向同一块内存,条件永远为真——这根本不是在比较元素内容。另外,重复检测的时机完全错误:应该在输入数据后、创建新节点前检查链表中是否已有相同元素,而不是遍历显示的时候才判断。

修正后的完整代码

#include <iostream>
#include <string>
    
using namespace std;

// 规范定义链表节点结构体
struct ListNode
{
    string name;
    int gpa;
    double courseHours;
    ListNode *prev;
    ListNode *next;
    // 构造函数自动初始化指针为nullptr,避免野指针
    ListNode() : prev(nullptr), next(nullptr) {}
};

// 辅助函数:检查链表中是否存在重复元素(按姓名+GPA判定重复,可按需调整)
bool isDuplicate(ListNode* head, const string& name, int gpa) {
    ListNode* current = head;
    while (current != nullptr) {
        if (current->name == name && current->gpa == gpa) {
            return true;
        }
        current = current->next;
    }
    return false;
}

// 遍历显示链表所有元素
void displayList(ListNode* head) {
    if (head == nullptr) {
        cout << "链表为空,无节点可显示" << endl;
        return;
    }
    ListNode* current = head;
    cout << "\n链表存储的数据:" << endl;
    while (current != nullptr) {
        cout << "姓名:" << current->name << endl;
        cout << "GPA:" << current->gpa << endl;
        cout << "-------------------------" << endl;
        current = current->next;
    }
}

int main()
{
    ListNode *head = nullptr;
    ListNode *tail = nullptr; // 记录尾节点,提升添加效率

    int addCount = 3; // 计划添加的元素数量
    for(int ctr = 1; ctr <= addCount; ctr++)
    {
        string inpName;
        int inpGpa;
        cout << "\n请输入第" << ctr << "个元素的姓名:";
        cin >> inpName;
        cout << "请输入第" << ctr << "个元素的GPA:";
        cin >> inpGpa;

        // 先检查重复,存在则跳过添加
        if (isDuplicate(head, inpName, inpGpa)) {
            cout << "数据已存在,跳过添加!" << endl;
            continue;
        }

        // 创建新节点并赋值
        ListNode* newNode = new ListNode();
        newNode->name = inpName;
        newNode->gpa = inpGpa;

        // 将新节点添加到链表尾部
        if (head == nullptr) {
            // 链表为空时,新节点既是头也是尾
            head = newNode;
            tail = newNode;
        } else {
            tail->next = newNode;
            newNode->prev = tail;
            tail = newNode;
        }
    }

    // 遍历显示所有元素
    displayList(head);

    // 注:实际项目中需手动释放链表内存,避免内存泄漏,此处简化处理
    return 0;
}

关键修改说明

  • 新增isDuplicate函数:专门遍历链表,比较元素的实际内容(姓名+GPA)来判断是否重复,解决了原代码指针地址比较的逻辑错误。
  • 调整检测时机:在输入数据后立即检查重复,避免创建无效节点。
  • 优化添加逻辑:用tail指针记录链表尾节点,添加元素时无需遍历到尾部,提升效率。
  • 拆分功能函数:把遍历显示逻辑封装成displayList,代码职责更清晰,避免原代码中遍历逻辑的混乱。

内容的提问来源于stack exchange,提问作者Code Apollo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:55:22