当前位置: 首页 > 建站教程

c语言数据结构怎么使用

时间:2026-01-28 13:50:44

在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;}

以上是一些常见数据结构的使用方法示例,当然还有其他更复杂的数据结构和操作方式,可以根据具体需求选择合适的数据结构。


上一篇:android中buildconfig的作用是什么
下一篇:android init进程日志怎么查看
c语言
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器
  • 英特尔第五代 Xeon CPU 来了:详细信息和行业反应
  • 由于云计算放缓引发扩张担忧,甲骨文股价暴跌
  • Web开发状况报告详细介绍可组合架构的优点
  • 如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳
  • 美光在数据中心需求增长后给出了强有力的预测
  • 2027服务器市场价值将接近1960亿美元
  • 生成式人工智能的下一步是什么?
  • 分享在外部存储上安装Ubuntu的5种方法技巧
  • 全球数据中心发展的关键考虑因素
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器

    英特尔第五代 Xeon CPU 来了:详细信息和行业反应

    由于云计算放缓引发扩张担忧,甲骨文股价暴跌

    Web开发状况报告详细介绍可组合架构的优点

    如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳

    美光在数据中心需求增长后给出了强有力的预测

    2027服务器市场价值将接近1960亿美元

    生成式人工智能的下一步是什么?

    分享在外部存储上安装Ubuntu的5种方法技巧

    全球数据中心发展的关键考虑因素