c语言数据结构怎么使用


在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 init进程日志怎么查看

下一篇:Python中tornado框架怎么使用


c语言
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器