c++链栈和链队的实现(类)

//链队
#include <iostream>

using namespace std;

struct qnode{
    int data;
    qnode *next;
};

class queue{
    public:
        queue():f(NULL),r(NULL)
        {}
        int front();
        void enqueue(int);
        void dequeue();
        bool empty();
        ~queue();
    private:
        qnode *f,*r;
};

int queue::front(){
    if(this->empty()){
        cout<<"队空,非法操作"<<endl;
    }
    return f->data;
}

void queue::enqueue(int data){
    qnode *p=new qnode;
    if(!p){
        cout<<"内存不足"<<endl;
        return ;
    }
    p->data=data;
    if(f==NULL){
        p->next=NULL;
        f=r=p;
    }
    p->next=NULL;
    r->next=p;
    r=p;
    return ;
}

void queue::dequeue(){
    if(r==NULL){
        cout<<"队空,操作违法"<<endl;
        return ;
    }
    else if(f==r){
        delete f;
        r=f=NULL;
        return ;
    }
    qnode *p=f;
    f=f->next;
    delete p;
}

bool queue::empty(){
    if(f==NULL)return true;
    return false;
}

queue::~queue(){
    qnode *p=f;
    while(!this->empty()){
        this->dequeue();
    }
    cout<<"delete finish!"<<endl;
}

int main()
{
    queue q;
    q.enqueue(1);
    q.dequeue();
    cout<<q.empty()<<endl;
    q.enqueue(10);
    q.enqueue(11);
    cout<<q.front()<<endl;
    return 0;
}
//链栈
#include <iostream>
#include<cstdio>

//breakÎÊÌâ

using namespace std;

struct stnode{
    int data;
    stnode *next;
};

class stack{
    public:
        stack():head(NULL)
        {}
        int top();
        void push(int data);
        void pop();
        bool empty();
        ~stack();
        void print();
    private:
        struct stnode *head;

};

int stack::top(){
    if(head==NULL){
        cout<<"Õ»¿Õ£¡";
        return 0;
    }
    return head->data;
}

void stack::print(){
    stnode *p=head;
    while(p){
        cout<<p->data<<" ";
        p=p->next;
    }
    cout<<endl;
}

void stack::push(int data){
    stnode *p=new stnode;
    if(!p){
        cout<<"ÄÚ´æ·ÖÅäʧ°Ü";
        return ;
    }
    p->data=data;

    if(head==NULL){
        head=p;
        head->next=NULL;
        return ;
    }

    p->next=head;
    head=p;
    return ;
}

void stack::pop(){
    if(this->empty()){
        cout<<"Õ»¿Õ"<<endl;
    }
    struct stnode *p=head;

    head=head->next;
    delete p;
}

stack::~stack(){
    stnode *p=head;
    while(head){
        p=head;
        head=head->next;
        delete p;
    }
}

bool stack::empty(){
    if(head==NULL)return true;
    return false;
}

int main()
{
    stack s;
    s.push(10);
    s.push(11);
    s.print();
    s.pop();
    cout<<s.top()<<endl;
    cout<<s.empty()<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值