2024年10月15日總結

离璨霂發表於2024-10-15

今天在課餘之間理了理棧與佇列的知識,以下是一個利用棧和佇列資料存取差異製作的判斷迴文序列的c語言程式

include<stdio.h>

include<stdlib.h>

include<math.h>

define MAXSIZE 100 //能儲存的字串最大達到100

define OK 0

define ERROR -1

typedef int Status;
typedef struct SqStack {
char* top; //定義棧頂指標
char* base; //定義棧底指標
int stacksize; //棧可用的最大容量
}SqStack;
//定義順序佇列的儲存結構
typedef struct SqQueue {
char* base; //儲存空間的基地址
int front; //頭指標
int rear; //尾指標
}SqQueue;

Status Creat_Stack(SqStack* S)
{
S->base = (char)malloc(sizeof(char) * MAXSIZE); //給棧動態分配記憶體,所分配的記憶體為100
if (!S->base)
{
printf("建立失敗!\n");
exit(OVERFLOW);
}
S->top = S->base;
S->stacksize = MAXSIZE;
return OK;
}
int IsEmpty_S(SqStack
S)
{
if (S->top == S->base)
return 1; //若為空,則返回1
return 0;
}
Status Push(SqStack* S, char a)
{
if (S->top - S->base == S->stacksize) //若棧滿
{
printf("棧已滿,無法插入!\n");
return ERROR;
}
S->top++ = a; //將a壓入棧中
return OK;
}
Status Pop(SqStack
S, char* a) //a為彈出的元素
{
int x = IsEmpty_S(S);
if (x) //判斷棧是否為空
{
printf("棧為空,無法刪除!\n");
return ERROR;
}
a = --S->top; //注意!!!!
return OK;
}
Status destory_S(SqStack
S)
{
free(S->base);
S->base = NULL;
S->top = NULL;
S->stacksize = 0;
return OK;
}
Status Creat_Q(SqQueue
Q)
{
Q->base = (char)malloc(sizeof(char) * MAXSIZE);
if (!Q->base)
{
printf("建立失敗!\n");
exit(OVERFLOW); //若記憶體分配失敗,則返回
}
Q->front = 0;
Q->rear = 0;
return OK;
}
Status In_Queue(SqQueue
Q, char a)
{
if ((Q->rear + 1) % MAXSIZE == Q->front) //尾指標在迴圈意義上加一後等於頭指標,隊滿
{
printf("佇列已滿,無法入隊!\n");
return ERROR;
}
Q->base[Q->rear] = a;
Q->rear = (Q->rear + 1) % MAXSIZE; //尾指標加一
return OK;
}
int IsEmpty_Q(SqQueue* Q)
{
if (Q->front == Q->rear)
return 1; //為空則返回1
return 0;
}
Status Out_Queue(SqQueue* Q, char* a) //用a記錄出隊的元素值
{
if (IsEmpty_Q(Q) == 1)
{
printf("佇列為空,無法出隊!\n");
return ERROR;
}
*a = Q->base[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
return OK;
}

//順序佇列的銷燬
Status destory_Q(SqQueue* Q)
{
free(Q->base);
Q->base = NULL;
Q->fr