MST
星途 面试题库

面试题:C语言数组名指针常量在复杂数据结构中的深度应用

定义一个结构体,结构体中包含一个字符数组和一个指向另一个相同结构体的指针。编写一个函数,接收结构体数组名(作为指针常量)作为参数,利用数组名指针常量的特性,实现一个链式存储结构,并将结构体数组中的元素按字符数组的字典序插入到该链式结构中。最后,编写一个函数遍历该链式结构并打印出每个结构体中字符数组的内容。
37.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

// 定义结构体
typedef struct Node {
    char str[100];
    struct Node* next;
} Node;

// 插入函数
void insert(Node** head, Node* newNode) {
    if (*head == NULL || strcmp(newNode->str, (*head)->str) < 0) {
        newNode->next = *head;
        *head = newNode;
    } else {
        Node* current = *head;
        while (current->next != NULL && strcmp(newNode->str, current->next->str) > 0) {
            current = current->next;
        }
        newNode->next = current->next;
        current->next = newNode;
    }
}

// 遍历函数
void traverse(Node* head) {
    Node* current = head;
    while (current != NULL) {
        printf("%s\n", current->str);
        current = current->next;
    }
}

int main() {
    Node arr[3] = {{"banana"}, {"apple"}, {"cherry"}};
    Node* head = NULL;

    for (int i = 0; i < 3; i++) {
        insert(&head, &arr[i]);
    }

    traverse(head);

    return 0;
}
  1. 结构体定义:定义了一个Node结构体,包含一个字符数组str和一个指向下一个Node的指针next
  2. 插入函数insert函数接收链表头指针的指针(因为要修改头指针)和要插入的新节点指针。根据字符数组的字典序将新节点插入到合适位置。
  3. 遍历函数traverse函数遍历链表并打印每个节点的字符数组内容。
  4. 主函数:定义了一个结构体数组arr,并将数组元素按字典序插入到链表中,最后遍历链表并打印内容。