您好,登錄后才能下訂單哦!
使用數組來保存數據,使用二級指針來保存棧中元素的地址
seqStack.h
#ifndef SEQ_STACK_H
#define SEQ_STACK_H
#include<stdlib.h>
#include<stdio.h>
#include<stdbool.h>
#include<memory.h>
typedef void SeqStack;
SeqStack* Stack_Create(int cap);
void Stack_Destroy(SeqStack* stack);
void Stack_Clear(SeqStack* stack);
int Stack_Push(SeqStack* stack, void* item);
void* Stack_Pop(SeqStack* stack);
void* Stack_Top(SeqStack* stack);
int Stack_Size(SeqStack* stack);
bool Stack_isFull(SeqStack* stack);
bool Stack_isEmpty(SeqStack* stack);
#endif //SEQ_STACK_H
seqStack.c
#include"seqStack.h"
typedef struct SeqStackStruct {
int size;
int cap;
unsigned int **data;
}MySeqStack;
SeqStack* Stack_Create(int cap) {
MySeqStack* myStack = (MySeqStack*)malloc(sizeof(MySeqStack));
if (myStack == NULL) {
fprintf(stderr,"malloc stack space error.\n");
return NULL;
}
myStack->data = (unsigned int**)malloc(cap * sizeof(unsigned int*));
memset(myStack->data, 0, cap * sizeof(unsigned int*));
myStack->size = 0;
myStack->cap = cap;
return (void *)myStack;
}
void Stack_Destroy(SeqStack* stack){
MySeqStack *myStack = (MySeqStack *)stack;
myStack->size = 0;
myStack->cap = 0;
free(myStack);
myStack = NULL;
}
void Stack_Clear(SeqStack* stack) {
MySeqStack *myStack = (MySeqStack *)stack;
myStack->size = 0;
}
int Stack_Push(SeqStack* stack, void* item) {
if (stack == NULL) {
return -1;
}
MySeqStack *myStack = (MySeqStack *)stack;
if (myStack->size >= myStack->cap) {
fprintf(stderr, "stack is Full.\n");
return -2;
}
myStack->size++;
myStack->data[myStack->size-1] = (unsigned int*)item;
}
bool Stack_isFull(SeqStack* stack) {
if (stack == NULL) {
return false;
}
MySeqStack *myStack = (MySeqStack *)stack;
return myStack->size == myStack->cap;
}
bool Stack_isEmpty(SeqStack* stack) {
if (stack == NULL) {
return false;
}
MySeqStack *myStack = (MySeqStack *)stack;
return myStack->size == 0;
}
void* Stack_Pop(SeqStack* stack) {
if (stack == NULL) {
return;
}
MySeqStack *myStack = (MySeqStack *)stack;
void *item = (void *)myStack->data[myStack->size - 1];
myStack->data[myStack->size - 1] = NULL;
myStack->size--;
return item;
}
void* Stack_Top(SeqStack* stack) {
if (stack == NULL) {
return;
}
MySeqStack *myStack = (MySeqStack *)stack;
return (void *)myStack->data[myStack->size - 1];
}
int Stack_Size(SeqStack* stack) {
if (stack == NULL) {
return 0;
}
MySeqStack *myStack = (MySeqStack *)stack;
return myStack->size;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。