网站首页 网站地图
网站首页 > 娱乐人生 > 数据结构怎么用c

数据结构怎么用c

时间:2026-03-18 21:05:38

在C语言中,实现数据结构可以通过以下几种方法:

静态数组

静态数组是C语言中最基本的数据结构之一,适用于数据量较小且固定的情况。

声明静态数组需要指定数组的类型、名称和大小。例如,声明一个包含10个整数的数组:

```c

int arr;

```

访问数组中的元素使用索引,索引从0开始。例如,访问数组中的第一个元素:

```c

arr = 1;

```

遍历数组中的所有元素可以使用循环:

```c

for (int i = 0; i < 10; i++) {

printf("%d ", arr[i]);

}

```

动态数组

动态数组使用指针和动态内存分配函数(如`malloc`、`realloc`、`free`)来实现,适用于数据量不固定且较大的情况。

例如,声明一个动态数组并初始化为10个整数:

```c

int* arr = (int*)malloc(10 * sizeof(int));

```

动态数组的优点是可以在运行时改变大小,但需要手动管理内存。

链表

链表由节点组成,每个节点包含数据和指向下一个节点的指针。

可以使用结构体来定义节点:

```c

struct Node {

int data;

struct Node* next;

};

```

创建节点并添加到链表:

```c

struct Node* head = NULL;

struct Node* node1 = (struct Node*)malloc(sizeof(struct Node));

node1->data = 1;

node1->next = NULL;

head = node1;

struct Node* node2 = (struct Node*)malloc(sizeof(struct Node));

node2->data = 2;

node2->next = NULL;

node1->next = node2;

```

遍历链表并打印节点的数据:

```c

struct Node* current = head;

while (current != NULL) {

printf("%d\n", current->data);

current = current->next;

}

```

栈是一种后进先出(LIFO)的数据结构,可以使用数组或链表来实现。

使用结构体定义栈:

```c

struct Stack {

int top;

int* arr;

int capacity;

};

```

初始化栈:

```c

void init(struct Stack* stack, int capacity) {

stack->top = -1;

stack->arr = (int*)malloc(capacity * sizeof(int));

stack->capacity = capacity;

}

```

压入元素:

```c

void push(struct Stack* stack, int item) {

if (stack->top == stack->capacity - 1) {

printf("Stack overflow!\n");

return;

}

stack->arr[++stack->top] = item;

}

```

弹出元素:

```c

int pop(struct Stack* stack) {

if (stack->top == -1) {

printf("Stack underflow!\n");

return -1;

}

return stack->arr[stack->top--];

}

```

队列

队列是一种先进先出(FIFO)的数据结构,可以使用数组或链表来实现。

使用结构体定义队列:

```c

struct Queue {

int front;

int rear;

int* arr;

int capacity;

int size;

};

```

初始化队列:

```c

void init(struct Queue* queue, int capacity) {

queue->front = queue->rear = -1;

queue->arr = (int*)malloc(capacity * sizeof(int));

queue->capacity = capacity;

queue->size = 0;

}

```

入队: