c语言实现数据结构栈和队列
作者:野牛程序员:2024-01-03 21:26:39C语言阅读 2619
栈(Stack)是一种后进先出(LIFO)的数据结构,队列(Queue)是一种先进先出(FIFO)的数据结构。以下是用C语言实现基本的栈和队列的示例代码:
#include <stdio.h> #include <stdlib.h> // 栈的结构定义 #define MAX_STACK_SIZE 100 typedef struct { int data[MAX_STACK_SIZE]; int top; } Stack; // 初始化栈 void initializeStack(Stack *stack) { stack->top = -1; } // 入栈 void push(Stack *stack, int value) { if (stack->top < MAX_STACK_SIZE - 1) { stack->data[++(stack->top)] = value; } else { printf("Stack overflow\\n"); } } // 出栈 int pop(Stack *stack) { if (stack->top >= 0) { return stack->data[(stack->top)--]; } else { printf("Stack underflow\\n"); return -1; } } // 队列的结构定义 #define MAX_QUEUE_SIZE 100 typedef struct { int data[MAX_QUEUE_SIZE]; int front; int rear; } Queue; // 初始化队列 void initializeQueue(Queue *queue) { queue->front = -1; queue->rear = -1; } // 入队 void enqueue(Queue *queue, int value) { if (queue->rear < MAX_QUEUE_SIZE - 1) { queue->data[++(queue->rear)] = value; if (queue->front == -1) { queue->front = 0; } } else { printf("Queue overflow\\n"); } } // 出队 int dequeue(Queue *queue) { if (queue->front <= queue->rear && queue->front != -1) { return queue->data[(queue->front)++]; } else { printf("Queue underflow\\n"); return -1; } } int main() { // 使用栈和队列的示例 Stack myStack; Queue myQueue; initializeStack(&myStack); initializeQueue(&myQueue); // 入栈操作 push(&myStack, 10); push(&myStack, 20); push(&myStack, 30); // 出栈操作 printf("Popped from stack: %d\\n", pop(&myStack)); printf("Popped from stack: %d\\n", pop(&myStack)); // 入队操作 enqueue(&myQueue, 50); enqueue(&myQueue, 60); enqueue(&myQueue, 70); // 出队操作 printf("Dequeued from queue: %d\\n", dequeue(&myQueue)); printf("Dequeued from queue: %d\\n", dequeue(&myQueue)); return 0; }
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c语言实现归并排序
- 下一篇:c语言数据结构顺序表和链表