在C語言中,數據結構可以通過定義結構體來實現。以下是一些常見的數據結構的使用方法示例:
#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;
}
#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;
}
#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;
}
以上是一些常見數據結構的使用方法示例,當然還有其他更復雜的數據結構和操作方式,可以根據具體需求選擇合適的數據結構。