队列,循环队列和栈的代码演示
首先是队列的:
#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct Queue { int* data; int head, tail; int length; } Queue; Queue* init(int n) { Queue *q = (Queue *)malloc(sizeof(Queue)); q->data = (int *)malloc(sizeof(int) * n); q->head = q->tail = 0; q->length = n; return q; } int empty(Queue* q) { return q->head == q->tail; } int front(Queue* q) { return q->data[q->head]; } int push(Queue* q, int val) { if (q == NULL) return 0; if (q->tail == q->length) return 0; //这个地方还有可能是循环队列,这里就会发生假溢出的现象 q->data[q->tail++] = val; return 1; } int pop(Queue* q) { if (q == NULL) return 0; if (empty(q)) return 0; q->head++; return 1; } void clear(Queue* q) { if (q == NULL) return; free(q->data); free(q); }
然后是通过修改所得到得循环队列 , 为了解决假溢出的情况:
#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct Queue { int* data; int head, tail; int length; int cnt;//加入了元素个数 } Queue; Queue* init(int n) { Queue *q = (Queue *)malloc(sizeof(Queue)); q->data = (int *)malloc(sizeof(int) * n); q->head = q->tail = q->cnt = 0;//这个初始化把q->cnt置空 q->length = n; return q; } int empty(Queue* q) { return q->cnt = 0 ;//这个判空之间是用cnt来判空 } int front(Queue* q) { return q->data[q->head]; } int push(Queue* q, int val) { if (q == NULL) return 0; if (q->cnt == q->length) return 0;//判满也发生了变化 q->data[q->tail] = val; if (q->tail == q->length) q->tail -= q->length;//如果队尾到了最后一个,就减去长度 q->cnt++; return 1; }
int pop(Queue* q) { if (q == NULL) return 0; if (empty(q)) return 0; q->head++; if (q->head = q->length) q->head -= q->length;//这个其实就是和队头一样的操作 q->cnt--; return 1; } void clear(Queue* q) { if (q == NULL) return; free(q->data); free(q); }
下面来说栈的代码演示,这个就比较简单了:
#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct Stack { int* data; int top; int size; } Stack; Stack* init(int n) { Stack* s = (Stack*)malloc(sizeof(Stack)); s->data = (int*)malloc(sizeof(int) * n); s->size = n; s->top = -1; return s; } int empty(Stack* s) { return s->top == -1; } int top(Stack* s) { if (empty(s)) { return 0; } return s->data[s->top]; } void clear(Stack* s) { if (s == NULL) return ; free(s->data); free(s); return; } int push(Stack* s,int val) { if (s == NULL) return 0; if (s->top + 1 == s->size) return 0; s->top++; s->data[s->top] = val; return 1; } int pop(Stack* s) { if (s == NULL) return 0; if (empty(s)) return 0; s->top -= 1; return 1; }