链表实现栈

//stackLink.h
#ifndef STACKLINK_H_INCLUDED
#define STACKLINK_H_INCLUDED

template <typename T>
class Node
{
public:
    T data;
    Node<T>* next;
};

template <typename T>
class StackLink{
private:
    Node<T> *head;
public:
    void push(T data);
    T pop();
    bool isEmpty();
    StackLink(){
    head=new  Node<T>();
    head->data=-1;
    head->next=0;
    }
    ~StackLink(){delete head;}
};

template <typename T>
void StackLink<T>::push(T data)
{
    Node<T> *p=new Node<T>();
    p->data=data;
    p->next=head->next;
    head->next=p;
}

template <typename T>
T StackLink<T>::pop()
{
    T res;
    res=head->next->data;
    head->next=head->next->next;
    delete head->next;
    return res;
}

template <typename T>
bool StackLink<T>::isEmpty()
{
    return head->next==0;
}
#endif // STACKLINK_H_INCLUDED

//bcd.h
#ifndef BCD_H_INCLUDED
#define BCD_H_INCLUDED
#include <iostream>
using namespace std;
class BCD
{
    private:
    int decimal, binary;
    public:
    BCD(int x);
    BCD();
    void setCode(int y);
    static int staticMethod();
    static int ninstence;
    int getBinary()
    {
        return binary;
    }
    void outputBCD();
    friend ostream& operator << (ostream & o, BCD& bcd);

};
BCD operator + (BCD& bcd1, BCD &bcd2);
ostream& operator << (ostream & o, BCD& bcd);

#endif // BCD_H_INCLUDED

//bcd.cpp
#include "bcd.h"
#include <cstring>
#include <cmath>
#include <iostream>
#include "stackLink.h"
using namespace std;
int BCD::ninstence=0;
BCD::BCD(int x)
{
    decimal=x;
    int y, n=0, b=0;
    while(x!=0)
    {
        y=x%10;
        x=x/10;
        b=b+(y<<n*4);
        n++;
    }
    binary=b;
    ninstence++;
}
int BCD::staticMethod()
{
    return ninstence;
}
/*BCD operator + (BCD& bcd1, BCD &bcd2)
{
    int x,y,z;
    x=bcd1.BCD2Dec(), y=bcd2.BCD2Dec();
    z=x+y;
    cout<<z<<endl;
    BCD bcd3(z,0);
    return bcd3;
}*/
void BCD::setCode(int x)
{
    binary=x;
    int y, n=0, d=0;
    int a[10]={1,10,100,1000,10000,100000,100000,1000000,100000000,1000000000};
    while(x!=0)
    {
        y=x%16;
        x=x/16;
        d=d+(y*a[n]);
        n++;
    }
    //cout<<d<<endl;
    decimal=d;
}
BCD::BCD()
{
    decimal=-1;
    binary=-1;
}
void BCD::outputBCD()
{
    int a=binary;
    char x, y;
    StackLink<char> stack;
    while(a!=0)
    {
        x=(a&15);
        a>>=4;
        stack.push(x);
    }
    while(!stack.isEmpty())
    {
        y=stack.pop();
        cout<<((y>>3)&1)<<((y>>2)&1)<<((y>>1)&1)<<(y&1)<<", ";
    }
    cout<<endl;
}
ostream& operator << (ostream & o, BCD &bcd)
{
    o<<dec<<"decimal="<<bcd.decimal<<", "<<"binary="<<hex<<bcd.binary;

    return o;
}

//main.cpp
#include <iostream>
#include "bcd.h"
#include "StackLink.h"

using namespace std;

int main()
{
    BCD obj1(6666642);
    obj1.outputBCD();
    return 0;
}

发布了5 篇原创文章 · 获赞 1 · 访问量 729

猜你喜欢

转载自blog.csdn.net/davidhan427/article/details/87208574