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;
}

测试:

猜你喜欢

转载自blog.csdn.net/hunzhangzui9837/article/details/83628365