思路分析
代碼實現:
typedef int STDataType;
typedef struct Stack
{int* a;int top;//下標int capacity;
}ST;
//棧的初始化
void STInit(ST* ps);
//棧的插入
void STPush(ST* ps, STDataType x);
//棧的刪除
void STPop(ST* ps);
//
int STSize(ST* ps);
//判斷棧是否為空
bool STEmpty(ST* ps);
//棧的銷毀
void STDestroy(ST* ps);
//訪問棧頂元素
STDataType STTop(ST* ps);
//棧的初始化
void STInit(ST* ps)
{assert(ps);ps->a = malloc(sizeof(STDataType) * 4);if (ps->a == NULL){perror("malloc fail");return;}ps->capacity = 4;ps->top = 0;//代表top表示的是棧頂元素的下一個位置:剛開始top指向的是第一個元素,表示0,當第一個元素插入后top++表示1
}
//棧的插入
void STPush(ST* ps, STDataType x)
{assert(ps);if (ps->top == ps->capacity){STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * ps->capacity * 2);//擴容到當前的二倍if (tmp == NULL){perror("realloc fail");return;}ps->a = tmp;ps->capacity *= 2;}ps->a[ps->top] = x;ps->top++;
}
//棧的刪除
void STPop(ST* ps)
{assert(ps);assert(!STEmpty(ps));ps->top--;/*在棧操作函數中,棧指針 ps 是操作棧的基礎,如果 ps 為 NULL,那么后續對 ps 指向的棧結構的任何訪問(如 ps->top)都會導致未定義行為,通常是程序崩潰。因此,在進行棧操作之前,需要先確保 ps 不是 NULLassert(!STEmpty(ps)); 實際上是在檢查棧不為空的情況下才繼續執行后續操作*/
}
//
int STSize(ST* ps)
{assert(ps);return ps->top;
}
//判斷棧是否為空
bool STEmpty(ST* ps)
{assert(ps);return ps->top == 0;
}
//棧的銷毀
void STDestroy(ST* ps)
{assert(ps);free(ps->a);ps->a = NULL;ps->top = 0;ps->capacity = 0;
}
//訪問棧頂元素
STDataType STTop(ST* ps)
{assert(ps);assert(!STEmpty(ps));return ps->a[ps->top-1];
}typedef struct {ST pushst;ST popst;} MyQueue;MyQueue* myQueueCreate() {MyQueue* obj=(MyQueue*)malloc(sizeof(MyQueue));if(obj==NULL){perror("malloc fail");return NULL;}STInit(&obj->pushst);STInit(&obj->popst);return obj;
}void myQueuePush(MyQueue* obj, int x) {STPush(&obj->pushst,x);
}int myQueuePop(MyQueue* obj) {//導數據if(STEmpty(&obj->popst)){while(!STEmpty(&obj->pushst)){STPush(&obj->popst,STTop(&obj->pushst));//將棧頂元素導入STPop(&obj->pushst);//刪除棧頂元素}}int front=STTop(&obj->popst);STPop(&obj->popst);return front;
}int myQueuePeek(MyQueue* obj) {//導數據if(STEmpty(&obj->popst)){while(!STEmpty(&obj->pushst)){STPush(&obj->popst,STTop(&obj->pushst));//將棧頂元素導入STPop(&obj->pushst);//刪除棧頂元素}}int front=STTop(&obj->popst);return front;
}bool myQueueEmpty(MyQueue* obj) {return STEmpty(&obj->pushst)&&STEmpty(&obj->popst);
}void myQueueFree(MyQueue* obj) {STDestroy(&obj->pushst);STDestroy(&obj->popst);free(obj);
}