自定义stack和queue
1.stack
#include <iostream>
#include <vector>
using namespace std;
class IStack
{
public:
virtual void push(const int &val) = 0;
virtual int pop() = 0; //返回栈顶的元素,c++的stack无此功能
virtual bool empty() = 0; //判空
virtual int size() = 0;
virtual int top() const = 0; //只读
};
class MyStack : public IStack
{
public:
MyStack();
~MyStack();
void push(const int &val);
int pop();
bool empty();
int size();
int top() const;
public:
vector<int> vec;
};
MyStack::MyStack()
{
}
MyStack::~MyStack()
{
}
void MyStack::push(const int &val)
{
vec.push_back(val);
}
int MyStack::pop()
{
int temp = vec.back();
vec.pop_back();
return temp;
}
bool MyStack::empty()
{
return vec.empty();
}
int MyStack::size()
{
return vec.size();
}
int MyStack::top() const
{
return vec.back();
}
void test()
{
MyStack s;
s.push(1);
s.push(2);
cout << s.pop() << endl;
cout << s.empty() << endl;
cout << s.size() << endl;
}
int main(int argc, char const *argv[])
{
test();
system("pause");
return 0;
}
2.队列
//队列最好使用deque或者链表, 因为这样涉及内存移动就比较小, vector不太适合
#include <iostream>
#include <deque>
using namespace std;
class IQueue
{
public:
virtual int front() const = 0;
virtual int back() const = 0;
virtual void push(const int &val) = 0;
virtual int pop() = 0;
virtual int size() = 0;
virtual bool empty() const = 0;
};
class MyQueue : public IQueue
{
public:
MyQueue();
~MyQueue();
int front() const;
int back() const;
void push(const int &val);
int pop();
int size();
bool empty() const;
public:
deque<int> deq; //队列最好使用deque或者链表
};
MyQueue::MyQueue()
{
}
MyQueue::~MyQueue()
{
}
int MyQueue::front() const
{
return deq.front();
}
int MyQueue::back() const
{
return deq.back();
}
void MyQueue::push(const int &val)
{
deq.push_front(val);
}
int MyQueue::pop()
{
int temp = deq.back();
deq.pop_back();
return temp;
}
int MyQueue::size()
{
return deq.size();
}
bool MyQueue::empty() const
{
return deq.empty();
}
void test()
{
MyQueue my;
for (int i = 0; i < 10; i++)
{
my.push(i);
}
cout << my.pop() << endl; //第一个进入的数据,并从队列中取消
cout << my.back() << endl; //取队尾数据,最后进入的
cout << my.size() << endl;
cout << my.empty() << endl;
cout << my.front() << endl; //队首数据
}
int main(int argc, char const *argv[])
{
test();
system("pause");
return 0;
}
dl;
cout << my.empty() << endl;
cout << my.front() << endl; //队首数据
}
int main(int argc, char const *argv[])
{
test();
system(“pause”);
return 0;
}