MST

星途 面试题库

面试题:C语言指针表达式在复杂数据结构中的优化

定义一个链表结构,节点包含一个整型数据和一个指向下一个节点的指针。现在需要编写一个函数,接收链表头指针,通过优化后的指针表达式找到链表中数据值最大的节点,并返回该节点指针。请详细描述优化思路并写出代码。
40.7万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
  1. 优化思路
    • 遍历链表时,我们只需要比较节点中的整型数据,不需要进行复杂的指针运算。每遍历到一个新节点,就将其数据与当前记录的最大值节点的数据进行比较,如果新节点数据更大,则更新最大值节点指针。这样,通过一次简单的线性遍历就能找到最大值节点,时间复杂度为 (O(n)),其中 (n) 是链表的节点数。空间复杂度为 (O(1)),因为只使用了几个指针变量。
  2. 代码如下(以C语言为例)
#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构
struct ListNode {
    int data;
    struct ListNode *next;
};

// 函数声明
struct ListNode* findMaxNode(struct ListNode* head);

int main() {
    // 构建一个简单链表用于测试
    struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->data = 3;
    struct ListNode* node2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    node2->data = 5;
    struct ListNode* node3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    node3->data = 1;
    head->next = node2;
    node2->next = node3;
    node3->next = NULL;

    struct ListNode* maxNode = findMaxNode(head);
    printf("最大值节点的数据: %d\n", maxNode->data);

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

    return 0;
}

// 函数定义,找到链表中数据值最大的节点
struct ListNode* findMaxNode(struct ListNode* head) {
    if (head == NULL) {
        return NULL;
    }
    struct ListNode* maxNode = head;
    struct ListNode* current = head->next;
    while (current != NULL) {
        if (current->data > maxNode->data) {
            maxNode = current;
        }
        current = current->next;
    }
    return maxNode;
}

如果是C++ 语言,代码如下:

#include <iostream>

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

// 函数声明
ListNode* findMaxNode(ListNode* head);

int main() {
    // 构建一个简单链表用于测试
    ListNode* head = new ListNode(3);
    head->next = new ListNode(5);
    head->next->next = new ListNode(1);

    ListNode* maxNode = findMaxNode(head);
    std::cout << "最大值节点的数据: " << maxNode->data << std::endl;

    // 释放链表内存
    ListNode* current = head;
    ListNode* next;
    while (current != nullptr) {
        next = current->next;
        delete current;
        current = next;
    }

    return 0;
}

// 函数定义,找到链表中数据值最大的节点
ListNode* findMaxNode(ListNode* head) {
    if (head == nullptr) {
        return nullptr;
    }
    ListNode* maxNode = head;
    ListNode* current = head->next;
    while (current != nullptr) {
        if (current->data > maxNode->data) {
            maxNode = current;
        }
        current = current->next;
    }
    return maxNode;
}