《面试准备》C++数组、链表实现栈

1、数组实现栈(加了模板)

#include <iostream>
using namespace std;
#define MAX 100
//数组实现栈:模板类
template<class T>
class MyStack
{
public:
    T * buf;
    T top;
public:
    MyStack(){
        buf = new T[MAX];
        top = -1;
    }
    ~MyStack(){
        delete [] buf;
        buf = NULL;
        cout<<"release buf"<<endl;
    }
    bool isempty();
    bool isfull();
    void push(T a);
    T    pop();         //返回栈顶元素
};

template<class T>
bool MyStack<T>::isempty(){
    if(top==-1)
        return true;
    return false;
}

template<class T>
bool MyStack<T>::isfull(){
    if(top==MAX-1)
        return true;
    return false;
}

template<class T>
void MyStack<T>::push(T a){
    if(isfull()){
        return;
    }
    top++;
    buf[top] = a;
}

template<class T>
T MyStack<T>::pop(){
    if(isempty()){
        return -1;
    }
    top--;\
    return buf[top];
}


int main ()
{
    MyStack<int> *mystack =new MyStack<int>();
    mystack->push(5);
    mystack->push(4);
    mystack->push(3);
    cout<<"top is : "<<mystack->pop()<<endl;
    for(int i=mystack->top;i>=0;i--){
        cout<<mystack->buf[i]<<endl;
    }
    delete mystack;             //调用析构函数,释放内存
    mystack = NULL;             //将指针指向NULL 否则将成为野指针
    return 0;
}

2、链表实现栈

#include <iostream>
#include <stack>
using namespace std;

//单向链表节点
struct ListNode{
    int value;
    struct ListNode *Next;
};

class MyStack
{
public:                           //成员变量位置
    ListNode *Head;
public:                           //成员函数位置
    MyStack(){
        Head = new ListNode;      //创建对象的时候调用
    }
    ~MyStack(){                   //析构函数一般用于释放内存
        delete Head;
        Head = NULL;
    }
    bool isempty();
    void pushback(int n);
    void pop();
    void egrodic();
};

bool MyStack::isempty(){
    ListNode *P = Head;
    if(P==NULL||P->Next==NULL)
        return true;
    return false;
}

void MyStack::pushback(int n){
    ListNode *P = Head;
    while(P->Next!=NULL){
        P = P->Next;
    }
    ListNode *tmp = new ListNode;
    tmp->value = n;
    tmp->Next =NULL;
    P->Next = tmp;
    P = tmp;
}

void MyStack::pop(){
    if(isempty())
        return;
    ListNode *P = Head;
    while(P->Next->Next!=NULL){
        P = P->Next;
    }
   P->Next = NULL;
}

void MyStack::egrodic(){
    if(isempty())
        return;
    ListNode *P = Head;
    while(P->Next!=NULL){
        P = P->Next;
        cout<<P->value<<endl;
    }
}

int main ()
{
    MyStack *mystack = new MyStack;    //自己定义一个对象
    mystack->pushback(2);
    mystack->pushback(3);
    mystack->pushback(4);
    mystack->pop();
    mystack->egrodic();
    delete mystack;
    mystack = NULL;
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值