1. 程式人生 > >c/c++ 陣列實現棧

c/c++ 陣列實現棧

方法一:結構體實現

#include <iostream>

using namespace std;

typedef struct{
    int d[10];
    int top;
}Stack;

/****初始化一個棧*****/
void init(Stack *s){
    s->top=-1;
}

/****判斷是否為空 ****/
bool em(Stack *s){
    if(-1==s->top)
        return true;
    else
        return false;
}

/****判斷是否為滿 ****/
bool full(Stack * s){
   if(9==s->top)
       return true;
   else
       return false;
}

/*******入棧*******/
bool push(Stack *s,int a){
   if(full(s))  //滿了就不能入棧
       return false;
   else{
       s->top++;  //指標先加
       s->d[s->top]=a;//再把資料存進對應的“格子”
       return true;
    }
}

/*******出棧*******/
int pop(Stack *s){
    if(em(s))    //空的當然不能出棧
        return -1;
    else{
        int tmp=s->d[s->top]; //把棧頂元素付給中間變數
        s->top--;         //指標減一
        return tmp;
    }
}

/****取棧頂元素****/
int top(Stack *s){
    int a;
    if(em(s)) //同理空棧沒有元素就不行
        return false;
    else{
        a=s->d[s->top]; //把棧頂的元素賦值即可
        return a;
    }
}

/****取有效元素長度****/
int len(Stack *s){
    return s->top+1;
}

/*****遍歷*****/
void ergodic(Stack *s){
    cout <<"遍歷:";
    for(int i=0;i<=s->top;i++)
        cout << s->d[i]<<" ";
}

int main(){
    Stack s;
    int a,lens;
    init(&s);
    push(&s,1);
    push(&s,2);
    push(&s,3);
    push(&s,4);
    push(&s,5);
    push(&s,6);
    int p =pop(&s);
    a = top(&s);      //取棧頂元素
    lens = len(&s);   //長度
    cout <<"出棧元素:"<<p<< endl;
    cout <<"棧頂元素:"<<a<< endl;
    cout <<"元素長度:"<<lens<< endl;
    ergodic(&s);      //遍歷
    return 0;
}

測試: 

方法2:封裝成class

#include <iostream>
#define MAX 10
using namespace std;

class Stack{
private:
    int top;
    int a[MAX];
public:
    Stack();
    bool Empty();
    bool full();
    bool push(int a);
    int pop();
    bool bianli();
};

Stack::Stack(){
    this->top = -1;
}

bool Stack::Empty(){
    if(this->top==-1)
        return true;
    return false;
}

bool Stack::full(){
    if(this->top==9)
        return true;
    return false;
}

bool Stack::push(int a){
    if(full())
        return false;
    this->top++;
    this->a[this->top] = a;
    return true;
}

bool Stack::bianli(){
    if(Empty())
        return false;
    for(int i=0;i<=this->top;i++){
        cout << this->a[i]<<" ";
    }
    return true;
}

int Stack::pop(){
    if(Empty())
        return false;
    int a = this->a[this->top];
    this->top--;
    return a;
}

int main()
{
    Stack s;
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);
    int b = s.pop();
    cout <<"出棧元素:"<< b << endl;
    cout <<"遍歷:";
    s.bianli();
    return 0;
}

測試: