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

如何在单链表pushFront函数中正确调用createNewNode函数?

单链表pushFront函数修正与参数传递指导

createNewNode参数含义

createNewNode的两个参数作用明确:

  • 第一个参数:节点要存储的value值,你已经正确传递了该参数。
  • 第二个参数:新节点的next指针需要指向的节点地址,这是你之前混淆的部分。

原代码关键错误

  • 变量n未声明类型,编译会直接报错。
  • 指针赋值语法错误:list.head -> n、n -> list.tail这类写法完全错误,更新指针需要用赋值运算符=,而非成员访问符->。
  • createNewNode第二个参数传递错误:空链表时未传合法值,非空链表时参数缺失。
  • 未更新链表的size属性,导致长度统计失效。
  • else分支代码不完整,缺少核心赋值逻辑。

修正后的完整代码

struct SingleLinkedListNode {
    int value;              //Integer value of the node
    SingleLinkedListNode* next = 0; //Pointer to the next node in the list
                //Next pointer is initialized to NULL
};

struct SingleLinkedList {
    SingleLinkedListNode* head = 0; //Pointer to the beginning of the list
    SingleLinkedListNode* tail = 0; //Pointer to the end of the list
    int size = 0;           //Counts the number of nodes in the list
};

SingleLinkedListNode* createNewNode(const int value, SingleLinkedListNode* next) {
    SingleLinkedListNode* n = new SingleLinkedListNode;
    n -> value = value;
    n -> next = next;

    return n;
}

void pushFront(SingleLinkedList& list, const int value) {
    SingleLinkedListNode* n = nullptr;
    // 链表为空的情况
    if (list.head == nullptr) {          
        // 空链表中,新节点没有后续节点,next传nullptr
        n = createNewNode(value, nullptr);
        // 头和尾都指向这个唯一节点
        list.head = n;
        list.tail = n;
    }
    // 链表已有节点的情况
    else {
        // 新节点的next指向原来的头节点,把新节点插在最前面
        n = createNewNode(value, list.head);
        // 更新头节点为新节点
        list.head = n;
    }
    // 插入节点后,链表长度加1
    list.size++;
}

修正逻辑说明

  1. 变量声明:显式声明SingleLinkedListNode* n,解决编译报错问题。
  2. 空链表处理:
    • 调用createNewNode(value, nullptr),因为空链表中新增节点没有后续节点,next设为nullptr。
    • 同时将list.head和list.tail指向新节点,此时链表仅有这一个节点。
  3. 非空链表处理:
    • 调用createNewNode(value, list.head),让新节点的next指针指向原头节点,完成头插的链接逻辑。
    • 更新list.head为新节点,正式将新节点设为链表的头。
  4. 更新长度:无论链表是否为空,插入节点后都要将list.size加1,保证长度统计准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:33:11