在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 100struct 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 100struct 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;}以上是一些常见数据结构的使用方法示例,当然还有其他更复杂的数据结构和操作方式,可以根据具体需求选择合适的数据结构。




