簡單資料結構---陣列實現棧
阿新 • • 發佈:2018-12-23
/* * File name : LinkList.cpp * Function : 陣列棧的C++實現 * Created on : 2016年4月20日 * Author : [email protected] * Copyright : 歡迎大家和我一起交流學習,轉載請保持原始檔的完整性。 任何單位和個人不經本人允許不得用於商業用途 */ #include <cstdio> #include <iostream> using namespace std; #define MAX 10 typedef struct Astack { int data[MAX]; int top; }Astack; void stack_init(Astack & S); void stack_clear(Astack & S); bool stack_is_empty(Astack & S); bool stack_get_top(Astack & S, int & elem); bool stack_push(Astack & S, int elem); bool stack_pop(Astack & S, int &elem); int stack_get_length(Astack & S); int main(int argc, char** argv) { Astack as; stack_init(as); cout << "Stack is empty ? " << stack_is_empty(as) << endl; stack_push(as, 10); stack_push(as, 11); stack_push(as, 12); stack_push(as, 13); cout << "Stack is empty ? " << stack_is_empty(as) << endl; cout << "The length of Stack as is : " << stack_get_length(as) << endl; int elem; stack_pop(as, elem); cout << "pop elem is : " << elem << endl; stack_pop(as, elem); cout << "pop elem is : " << elem << endl; stack_pop(as, elem); cout << "pop elem is : " << elem << endl; stack_pop(as, elem); cout << "pop elem is : " << elem << endl; stack_pop(as, elem); return 0; } void stack_init(Astack & S) { S.top = -1; } void stack_clear(Astack & S) { S.top =-1; } bool stack_is_empty(Astack & S) { return (S.top == -1) ? true : false; } bool stack_get_top(Astack & S, int & elem) { if (S.top == -1) return false; elem = S.data[S.top]; return true; } bool stack_push(Astack & S, int elem) { if (S.top == MAX - 1) { cout << "Stack is full, can not push !" << endl; return false; } S.data[++S.top] = elem; return true; } bool stack_pop(Astack & S, int &elem) { if (S.top == -1) { cout << "Stack is empty, can not pop !" << endl; return false; } elem = S.data[S.top--]; return true; } int stack_get_length(Astack & S) { return S.top+1; }