Data Structures in C: Practical Examples
In the C language, data structures can be implemented by defining structures. Here are some common examples of how data structures are used:
- Linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
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;
// 遍历链表并打印节点的数据
struct Node* current = head;
while (current != NULL) {
printf("%d\n", current->data);
current = current->next;
}
return 0;
}
- Shelves:
#include <stdio.h>
#define MAX_SIZE 100
struct Stack {
int data[MAX_SIZE];
int top;
};
void push(struct Stack* stack, int value) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack is full.\n");
return;
}
stack->data[++stack->top] = value;
}
int pop(struct Stack* stack) {
if (stack->top == -1) {
printf("Stack is empty.\n");
return -1;
}
return stack->data[stack->top--];
}
int main() {
struct Stack stack;
stack.top = -1;
push(&stack, 1);
push(&stack, 2);
printf("%d\n", pop(&stack));
printf("%d\n", pop(&stack));
return 0;
}
- line:
#include <stdio.h>
#define MAX_SIZE 100
struct Queue {
int data[MAX_SIZE];
int front, rear;
};
void enqueue(struct Queue* queue, int value) {
if (queue->rear == MAX_SIZE - 1) {
printf("Queue is full.\n");
return;
}
queue->data[++queue->rear] = value;
}
int dequeue(struct Queue* queue) {
if (queue->front > queue->rear) {
printf("Queue is empty.\n");
return -1;
}
return queue->data[queue->front++];
}
int main() {
struct Queue queue;
queue.front = 0;
queue.rear = -1;
enqueue(&queue, 1);
enqueue(&queue, 2);
printf("%d\n", dequeue(&queue));
printf("%d\n", dequeue(&queue));
return 0;
}
Here are some examples of common data structures and how to use them. Of course, there are also more complex data structures and ways of operating, so you can choose the appropriate data structure based on your specific needs.