MST
星途 面试题库

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

假设有一个结构体定义如下: ```c struct Node { int data; struct Node *next; }; ``` 编写一个函数 `void traverseAndModify(struct Node *head)`,该函数通过指针解引用遍历链表,将每个节点的数据值替换为其数据值与下一个节点数据值之和(最后一个节点的数据值保持不变)。请给出完整的C语言代码实现,包括链表的创建和函数调用部分。
48.7万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

// 创建新节点
struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->next = NULL;
    return newNode;
}

// 遍历并修改链表
void traverseAndModify(struct Node *head) {
    struct Node* current = head;
    while (current != NULL && current->next != NULL) {
        current->data = current->data + current->next->data;
        current = current->next;
    }
}

// 打印链表
void printList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

int main() {
    // 创建链表 1 -> 2 -> 3 -> 4
    struct Node* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);

    printf("Original List: ");
    printList(head);

    traverseAndModify(head);

    printf("Modified List: ");
    printList(head);

    // 释放链表内存
    struct Node* current = head;
    struct Node* nextNode;
    while (current != NULL) {
        nextNode = current->next;
        free(current);
        current = nextNode;
    }

    return 0;
}