在數據結構中,棧是一種很重要的存在。這是一種先進後出的結構,就像一個“死胡同”一樣。今天我們先用最簡單的方式靜態數組來模擬棧。代碼上傳至 https://github.com/chenyufeng1991/Stack_StaticArray。
(1)聲明棧的大小,數組,和一個棧頂指針。棧頂指針可以取出棧頂的數據。
#define STACK_SIZE 50 static int stack[STACK_SIZE]; static int top_element = -1;
//壓入元素
void push(int value){
if (!isFull()) {
stack[++top_element] = value;
}
}
//彈出元素
void pop(){
if (!isEmpty()) {
top_element--;
}
}
//取頂部元素
int top(){
if (!isEmpty()) {
return stack[top_element];
}
return -32768;
}
//判斷棧是否為空
int isEmpty(){
return top_element == -1;
}
(6)判斷棧是否已滿
//判斷棧是否已滿
int isFull(){
return top_element == STACK_SIZE - 1;
}
(7)打印棧元素,只能通過從頂部開始打印
//從頂部開始打印棧元素
void printStack(){
int i = top_element;
printf("%s函數執行,打印出靜態數組棧裡面的值:\n",__FUNCTION__);
if (i == -1) {
printf("這是一個空棧\n");
}else{
while (i != -1) {
printf("%d ",stack[i--]);
}
printf("\n");
}
}
(8)測試代碼
int main(int argc, const char * argv[]) {
push(4);push(6);push(1);push(9);push(2);push(8);
printStack();
printf("\n");
pop();pop();pop();pop();
printf("經過pop後棧的元素為:\n");
printStack();
printf("\n");
printf("top元素的值:%d\n",top());
return 0;
}