其他分享
首页 > 其他分享> > 栈的表示

栈的表示

作者:互联网

 栈是一种后进先出(LIFO)的数据结构

 

 当熟悉了之后也可以去调用其他类似的api来完成逻辑

template<class T>
class QStack : public QVector<T>
{
public:
    // compiler-generated special member functions are fine!
    inline void swap(QStack<T> &other) Q_DECL_NOTHROW { QVector<T>::swap(other); } // prevent QVector<->QStack swaps
    inline void push(const T &t) { QVector<T>::append(t); }
    T pop();
    T &top();
    const T &top() const;
};

 

 接下来就是敲代码动手实现。

C++实现:

ArrayStack.h
#pragma  once
#define STACK_SIZE 100
typedef int DataType;

class ArrayStack {
public :
    ArrayStack();
    DataType& top();
    void push(  const DataType &e);
    DataType pop();
    bool isEmpty();
    int length();
    void clear();
private :
    DataType m_stack[STACK_SIZE];
    int m_top;   //top为栈顶指针

};
ArrayStack.cpp  
#include "ArrayStack.h"
#include <iostream>
#include <cassert>
#define  Debug 1
ArrayStack ::ArrayStack():m_top(0) {
#if Debug
    std::cout<<"初始化ArrayStack";
#endif
}



DataType  &ArrayStack::top() {
    assert(!isEmpty());
    return m_stack[m_top -1];;
}


void ArrayStack::push(const DataType &e) {
    assert(m_top<STACK_SIZE);
    m_stack[m_top]=e;
    m_top++;
}


DataType ArrayStack::pop() {
    assert(!isEmpty());
    m_top--;
#if Debug
    std::cout<<"出栈元素:"<< m_stack[m_top];
#endif
    return m_stack[m_top];;

}


void ArrayStack::clear() {
    m_top=0;
}

int ArrayStack::length() {
    return m_top;
}

bool ArrayStack::isEmpty() {
    return m_top==0;
}

 

python实现: 

class ArrayStack:
    def __init__(self):
        """Create an empty stack"""
        self._data = []   # nonpublic list instance

    def __len__(self):
        """Return the numbers of elememts in the stack"""
        return len(self._data)

    def is_empty(self):
        """Return True is the stack is empty."""
        return len(self._data) == 0

    def push(self, e):
        """Add element e to the top of the stack"""
        self._data.append(e)

    def pop(self):
        """Remove and return the element from the top of the stack
            Raise Empty exception if the stack is empty
        """
        if self.is_empty():
            print('Stack is empty')
        else:
            return self._data.pop()

    def top(self):
        """Return(but do not remove) the element at the top of the Stack
           Raise Empty exception if the stack is empty
        """
        if self.is_empty():
            print('Stack is empty')
        else:
            return self._data[-1]

 

标签:表示,self,top,._,ArrayStack,stack,empty
来源: https://www.cnblogs.com/logmagic/p/16597400.html