在平时写OJ的题目的过程中,发现有很地方用到了队列和栈,但是c语言不像c++有stl库可以调用
于是这里手工实现了队列和栈,方便平时刷题使用:
队列的实现:
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> // you can define youself struct // for example : // typedef struct Position { // int x; // int y; // } Element; typedef int Element; #define MAX_QUEUE_LENGTH 10 struct Queue { Element queue[MAX_QUEUE_LENGTH]; int front; int rear; int length; }; void Init(struct Queue* queue) { memset(queue->queue, 0, sizeof(Element) * MAX_QUEUE_LENGTH); queue->front = 0; queue->rear = MAX_QUEUE_LENGTH - 1; queue->length = 0; } int Empty(struct Queue* queue) { return queue->length == 0; } void Push(struct Queue* queue, Element elem) { if (queue->length == MAX_QUEUE_LENGTH) { return; } else { queue->rear++; if (queue->rear == MAX_QUEUE_LENGTH) { queue->rear = 0; } queue->queue[queue->rear] = elem; queue->length++; } } void Pop(struct Queue* queue) { if (queue->length == 0) { return; } else { queue->front++; if (queue->front == MAX_QUEUE_LENGTH) { queue->front = 0; } queue->length--; } } Element Front(struct Queue* queue) { return queue->queue[queue->front]; } // following is test code, you can use like this: // int main() // { // struct Queue queue; // Init(&queue); // for (int i = 0; i < 120; i++) { // Push(&queue, i); // } // while (!Empty(&queue)) { // int t = Front(&queue); // printf("%d\n", t); // Pop(&queue); // } // return 0; // }
栈的实现:
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> // you can define youself struct // for example : // typedef struct Position { // int x; // int y; // } Element; typedef int Element; #define MAX_STACK_LENGTH 10 struct stack { Element stack[MAX_STACK_LENGTH]; int length; }; void Init(struct stack* stack) { memset(stack->stack, 0, sizeof(Element) * MAX_STACK_LENGTH); stack->length = 0; } int Empty(struct stack* stack) { return stack->length == 0; } void Push(struct stack* stack, Element elem) { if (stack->length == MAX_STACK_LENGTH) { return; } else { stack->stack[stack->length++] = elem; } } void Pop(struct stack* stack) { if (stack->length == 0) { return; } else { stack->length--; } } Element Top(struct stack* stack) { return stack->stack[stack->length - 1]; } // following is test code, you can use like this: // int main() // { // struct stack stack; // Init(&stack); // for (int i = 0; i < 120; i++) { // Push(&stack, i); // } // while (!Empty(&stack)) { // int t = Top(&stack); // printf("%d\n", t); // Pop(&stack); // } // return 0; // }