数据结构之栈复杂数据应用实现(2)

#include<iostream>
#include"MyStack.h"
using namespace std;
/*
    栈
    要求:
    1.定义Coordinate坐标类
    2.改造栈类,使其可以适用于坐标类
    目的:理解抽象数据类型在栈中的应用
*/
int main(){
    Coordinate c1(1, 2);
    Coordinate c2(1, 3);
    Coordinate c3(1, 4);

    MyStack *pStack = new MyStack(4);

    pStack->push(c1);
    pStack->push(c2);
    pStack->push(c3);

    pStack->stackTraverse();

    delete pStack;
    pStack = NULL;
    return 0;
}
#ifndef COORDINATE_H
#define COORDINATE_H

class Coordinate
{
public:
    Coordinate(){}
    Coordinate(int x, int y);
    void printCoordinate();

private:
    int m_iX;
    int m_iY;

};

#endif
#include"Coordinate.h"
#include<iostream>
using namespace std;
Coordinate::Coordinate(int x, int y) :m_iX(x), m_iY(y){

}

void Coordinate::printCoordinate(){
    cout << "(" << m_iX << "," << m_iY << ")" << endl;
}
#ifndef MYSTACK_H
#define MYSTACK_H
#include"Coordinate.h"
class MyStack
{
public:
    MyStack(){}
    MyStack(int size);      //分配栈空间
    ~MyStack();
    bool stackEmpty();
    bool stackFull();
    void clearStack();
    int stackLength();
    bool push(Coordinate elem);
    bool pop(Coordinate &elem);
    void stackTraverse();
private:
    Coordinate *m_pBuffer;  //栈空间指针
    int m_iSize;        //栈容量
    int m_iTop;         //栈顶,栈中元素个数

};

#endif
#include "MyStack.h"
#include<iostream>
#include"Coordinate.h"
using namespace std;
MyStack::MyStack(int size){
    m_iSize = size;
    m_iTop = 0;
    m_pBuffer = new Coordinate[size];
}

MyStack::~MyStack(){
    delete[] m_pBuffer;
    m_pBuffer = nullptr;
}

bool MyStack::stackEmpty(){
    if (0==m_iTop)
        return true;
    return false;
}

bool MyStack::stackFull(){
    if (m_iTop == m_iSize)
        return true;
    return false;
}

void MyStack::clearStack(){
    m_iTop = 0;
}

int MyStack::stackLength(){
    return m_iTop;
}

bool MyStack::push(Coordinate elem){
    if (stackFull())
        return false;
    m_pBuffer[m_iTop++] = elem;
    return true;
}

bool MyStack::pop(Coordinate &elem){
    if (stackEmpty())
        return false;
    m_iTop--;
    elem = m_pBuffer[m_iTop];
    return true;
}

void MyStack::stackTraverse(){

    for (int i = 0; i < m_iTop; i++)
        m_pBuffer[i].printCoordinate();

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值