C语言int数组与其他数据结构的转换

   2024-10-01 2750
核心提示:在C语言中,int数组是一种常见的数据结构,用于存储整数值。要将int数组与其他数据结构进行转换,你需要了解这些数据结构的特点

在C语言中,int数组是一种常见的数据结构,用于存储整数值。要将int数组与其他数据结构进行转换,你需要了解这些数据结构的特点以及如何在它们之间进行转换。以下是一些常见的数据结构及其与int数组之间的转换方法:

字符串(char数组)

int数组转换为字符串:

#include<stdio.h>#include<string.h>int main() {    int arr[] = {1, 2, 3, 4, 5};    int n = sizeof(arr) / sizeof(arr[0]);    char str[n * 4 + 1]; // 为每个整数分配4个字符(包括负号和空格),再加上一个终止符'\0'    for (int i = 0; i < n; i++) {        sprintf(str + i * 4, "%d ", arr[i]);    }    str[n * 4] = '\0'; // 添加终止符    printf("String: %s\n", str);    return 0;}
链表(struct定义的链表)

int数组转换为链表:

#include<stdio.h>#include <stdlib.h>typedef struct Node {    int data;    struct Node* next;} Node;Node* create_node(int data) {    Node* new_node = (Node*)malloc(sizeof(Node));    new_node->data = data;    new_node->next = NULL;    return new_node;}Node* array_to_linked_list(int arr[], int n) {    Node* head = create_node(arr[0]);    Node* current = head;    for (int i = 1; i < n; i++) {        current->next = create_node(arr[i]);        current = current->next;    }    return head;}void print_linked_list(Node* head) {    Node* current = head;    while (current != NULL) {        printf("%d -> ", current->data);        current = current->next;    }    printf("NULL\n");}int main() {    int arr[] = {1, 2, 3, 4, 5};    int n = sizeof(arr) / sizeof(arr[0]);    Node* linked_list = array_to_linked_list(arr, n);    print_linked_list(linked_list);    return 0;}
二叉树(struct定义的二叉树)

int数组转换为二叉搜索树(BST):

#include<stdio.h>#include <stdlib.h>typedef struct TreeNode {    int data;    struct TreeNode* left;    struct TreeNode* right;} TreeNode;TreeNode* create_tree_node(int data) {    TreeNode* new_node = (TreeNode*)malloc(sizeof(TreeNode));    new_node->data = data;    new_node->left = NULL;    new_node->right = NULL;    return new_node;}TreeNode* insert_into_bst(TreeNode* root, int data) {    if (root == NULL) {        return create_tree_node(data);    }    if (data< root->data) {        root->left = insert_into_bst(root->left, data);    } else {        root->right = insert_into_bst(root->right, data);    }    return root;}TreeNode* array_to_bst(int arr[], int n) {    TreeNode* root = NULL;    for (int i = 0; i < n; i++) {        root = insert_into_bst(root, arr[i]);    }    return root;}void inorder_traversal(TreeNode* root) {    if (root == NULL) {        return;    }    inorder_traversal(root->left);    printf("%d -> ", root->data);    inorder_traversal(root->right);}int main() {    int arr[] = {1, 2, 3, 4, 5};    int n = sizeof(arr) / sizeof(arr[0]);    TreeNode* bst = array_to_bst(arr, n);    inorder_traversal(bst);    printf("NULL\n");    return 0;}

这些示例展示了如何将int数组转换为其他数据结构。请注意,这些示例仅用于演示目的,实际应用中可能需要根据具体需求进行调整。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号