1. 程式人生 > 其它 >佇列,迴圈佇列和棧的程式碼演示

佇列,迴圈佇列和棧的程式碼演示

首先是佇列的:

#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;

}