栈、循环队列的基本操作

来源:互联网 发布:淘宝网理发店挂画 编辑:程序博客网 时间:2024/05/19 13:17

队列的基本操作

queue.h
#include <malloc.h>#include <string.h>#define TRUE1#define FALSE0#define MAX100typedef int status;typedef int ElemType;typedef struct _queue{ElemType *arr;int rear;int length;}queue;int initqueue(queue *s);int enqueue(queue *s, ElemType x);int dequeue(queue *s, ElemType *x);int destroyqueue(queue *s);status IsEmptyQueue(queue *s);#endif

queue.c
#include "queue.h"status initqueue(queue *s){s->arr = (ElemType *)malloc(sizeof(ElemType) * MAX);s->rear = 0;s->length = 0;memset(s->arr, 0, sizeof(ElemType) * MAX);return 1;}status enqueue(queue *s, ElemType x){int head;head = ((s->rear + MAX) - s->length) % MAX;if((s->rear + 1 % MAX) == head){printf("队满, head = %d, rear = %d, length = %d\n", head, s->rear, s->length);return 0;}s->arr[s->rear] = x;s->rear = (s->rear + 1) % MAX;s->length++;return 1;}status dequeue(queue *s, ElemType *x){int head;head = ((s->rear + MAX) - s->length) % MAX;if(head == s->rear){printf("队空, head = %d, rear = %d, length = %d\n", head, s->rear, s->length);return 0;}*x = s->arr[head];s->length--;return 1;}status IsEmptyQueue(queue *s){int head;head = ((s->rear + MAX) - s->length) % MAX;if(head == s->rear){return TRUE;}else{return FALSE;}}status destroyqueue(queue *s){free(s->arr);return 1;}

栈的基本操作

stack.h

#ifndef __STACK_H__#define __STACK_H__#include <stdio.h>#include <malloc.h>#include <string.h>#include "BiTree.h"#define STACKINCREMENT 10typedef struct BiTNode *elemtype;typedef int status;typedef struct _stack{elemtype *base;elemtype *top;int stacksize;}stack;#endif
stack.c
#include "stack.h"status initStack(stack *s){s->base = (elemtype *)malloc(sizeof(elemtype) * MAX);memset(s->base, 0, sizeof(elemtype) * MAX);s->top = s->base;s->stacksize = MAX;return TRUE;}status destroyStack(stack *s){free(s->base);return TRUE;}status clearStack(stack *s){s->top = s->base;return TRUE;}status StackEmpty(stack *s){return (s->top == s->base) ? TRUE : FALSE;}status Push(stack *s, elemtype x){if((s->top - s->base) >= s->stacksize){s->base = (elemtype *)realloc(s->base, s->stacksize + STACKINCREMENT);s->top = s->base + s->stacksize;s->stacksize += STACKINCREMENT;return FALSE;}*s->top++ = x;return TRUE;}status Pop(stack *s, elemtype *x){if(s->top == s->base){printf("栈空\n");return FALSE;}*x = *--s->top;return TRUE;}status GetTop(stack *s, elemtype *x){if(s->top == s->base){printf("栈空\n");return FALSE;}*x = *(s->top - 1);return TRUE;}


原创粉丝点击