数据结构之栈及应用(c++版)

来源:互联网 发布:java md5加密与解密 编辑:程序博客网 时间:2024/06/02 05:05

Stack.h

#pragma oncetemplate<typename T>class Node{public:    Node():last(nullptr) {};    Node(const T& v):value(v),last(nullptr){}    Node*& getlast() { return last; }    T& getvalue(){ return value; }private:    Node* last;    T value;};template<typename T>class Stack{public:    Stack():counts(0),tail(nullptr){}    void push(const T& item);    T pop();    bool isEmpty()const;    int size()const;private:    int counts;    Node<T>* tail;};template<typename T>void Stack<T>::push(const T& item){    Node<T>* top = new Node<T>;    top->getlast() = tail;    tail = top;    top->getvalue() = item;    ++counts;}template<typename T>bool Stack<T>::isEmpty() const{    return counts == 0;}template<typename T>T Stack<T>::pop(){    if (isEmpty())        exit(EXIT_FAILURE);    T ret = tail->getvalue();    Node<T>* topop = tail;    tail = tail->getlast();    --counts;    delete topop;    topop = nullptr;    return ret;}template<typename T>int Stack<T>::size() const{    return counts;}

测试及应用(用于求括号算术表达式的值)
Evaluate.h

#pragma once#include "Stack.h"#include <string>#include <sstream>#include <iterator>#include <algorithm>class Evaluate{public:    Evaluate(std::string s):exp(s) {};    operator double();private:    Stack<std::string> ops;    Stack<double> value;    std::string exp;};Evaluate::operator double(){    std::istringstream is(exp);    std::istream_iterator<std::string> part(is);    auto f = [this](const std::string& s) mutable    {        if (s == "(");        else if (s == "+")            ops.push("+");        else if (s == "-")            ops.push("-");        else if (s == "*")            ops.push("*");        else if (s == "/")            ops.push("/");        else if (s == ")")        {            double v = value.pop();            std::string op = ops.pop();            if (op == "+")                v = v + value.pop();            else if (op == "-")                v = v - value.pop();            else if (op == "*")                v = v * value.pop();            else if (op == "/")                v = v / value.pop();            value.push(v);        }        else        {            std::stringstream ss(s);            double get;            ss >> get;            value.push(get);        }    };    for_each(part, std::istream_iterator<std::string>(), f);    return value.pop();}

main.cpp

#include <iostream>#include "Stack.h"#include <string>#include "Evaluate.h"using namespace std;int main(){    Evaluate ca("( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )");    cout << ca << endl;    double b = ca + 3;    cout << b;    system("pause");    return 0;}
阅读全文
1 0