MST

星途 面试题库

面试题:C语言指针在复杂数据结构中的应用

设计一个链表结构,节点包含数据域和指针域,数据域为int类型,指针域指向下一个节点。编写一个函数,该函数接收链表头指针,能够实现将链表中所有节点的数据域值翻倍的功能,并说明函数内部指针操作的关键步骤和可能出现的问题及解决方案。
22.1万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>

// 定义链表节点结构
struct ListNode {
    int data;
    ListNode* next;
    ListNode(int val) : data(val), next(nullptr) {}
};

// 函数实现将链表中所有节点的数据域值翻倍
void doubleValues(ListNode* head) {
    ListNode* current = head;
    while (current != nullptr) {
        current->data *= 2;
        current = current->next;
    }
}

// 辅助函数:打印链表
void printList(ListNode* head) {
    ListNode* current = head;
    while (current != nullptr) {
        std::cout << current->data << " ";
        current = current->next;
    }
    std::cout << std::endl;
}

// 辅助函数:释放链表内存
void freeList(ListNode* head) {
    ListNode* current = head;
    ListNode* nextNode;
    while (current != nullptr) {
        nextNode = current->next;
        delete current;
        current = nextNode;
    }
}

你可以这样使用上述代码:

int main() {
    // 创建链表 1 -> 2 -> 3
    ListNode* head = new ListNode(1);
    head->next = new ListNode(2);
    head->next->next = new ListNode(3);

    std::cout << "Original list: ";
    printList(head);

    doubleValues(head);

    std::cout << "Doubled list: ";
    printList(head);

    freeList(head);
    return 0;
}

函数内部指针操作的关键步骤:

  1. 初始化指针:定义一个指针 current 并使其指向链表头节点 head
  2. 遍历链表:通过 while 循环,在 current 不为 nullptr 的情况下,不断移动 current 到下一个节点。
  3. 数据翻倍:在每次循环中,将 current 所指向节点的数据域 data 乘以 2。
  4. 移动指针:通过 current = current->nextcurrent 移动到下一个节点,以便处理下一个节点的数据。

可能出现的问题及解决方案:

  1. 空链表:如果传入的 headnullptr,函数应能正确处理,在上述实现中,while 循环条件可以处理这种情况,因为 current 初始化为 head,如果 headnullptr,循环不会执行。
  2. 内存泄漏:在处理链表时,如果在修改数据过程中发生异常,可能会导致部分节点内存未释放。为避免这种情况,在使用完链表后,需要编写释放链表内存的函数(如 freeList 函数),在程序结束前调用以确保所有节点内存被正确释放。