码迷,mamicode.com
首页 > 编程语言 > 详细

栈 - 数据结构C++实现

时间:2016-08-23 23:15:27      阅读:374      评论:0      收藏:0      [点我收藏+]

标签:

参考链接:数据结构探险—栈篇

学了队列之后,栈就很简单了,换汤不换药。

课程笔记:

 


栈的模型

 

栈的编程实现

 

栈的基本元素

 

栈的基本操作

 

基本操作的实现

 

C++实现步骤

 

标准C++代码

//MyStack.h
#pragma once
class MyStack
{
public:
    MyStack(int size);
    ~MyStack();
    bool stackEmpty();
    bool stackFull();
    void clearStack();
    int stackLength();
    bool push(char elem);
    bool pop(char &elem);
    void stackTraverse();
private:
    char *m_pBuffer;
    int m_iSize;
    int m_iTop;
};
//MyStack.cpp
#include"MyStack.h"
#include<iostream>
using namespace std;

MyStack::MyStack(int size)
{
    m_iSize = size;
    m_pBuffer = new char[size];
    m_iTop = 0;
}

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

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(char elem)
{
    if (stackFull())
    {
        return false;
    }
    m_pBuffer[m_iTop] = elem;
    m_iTop++;
    return true;
}

bool MyStack::pop(char &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++)
    {
        cout << m_pBuffer[i] << ",";
    }
}
//demo.cpp
#include<iostream>
#include"MyStack.h"
using namespace std;

int main()
{
    MyStack *p = new MyStack(5);

    p->push(h);
    p->push(e);
    p->push(l);
    p->push(i);
    p->push(z);

    p->stackTraverse();

    char tmp = 0;
    p->pop(tmp);
    cout << endl << "ding is " << tmp << endl;

    p->clearStack();

    cout << p->stackLength() << endl;

    if (p->stackEmpty())
    {
        cout << "stack is empty" << endl;
    }
    if (p->stackFull())
    {
        cout << "stack is full" << endl;
    }
    delete p;
    p = nullptr;
    return 0;
}

 

 

实际应用

栈 - 数据结构C++实现

标签:

原文地址:http://www.cnblogs.com/leezx/p/5801055.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!