设置一个vlist线性表类,抽象函数in(),out(),表示进表和出表,由Stack类和Quene类继承vlist,实现vlist指针既能是栈也可以是队列的功能。同时还可对不同的数据类型进行进表和出表。 代码提示 template class vlist//定义抽象类vlist, { public: virtual void in(T &e)=0; virtual T out()=0; }; template class Element//定义线性表元素,用于存储数据 { public: T data; Element *next; Element(){} }; 编程要求 根据提示,在右侧编辑器补充代码。 测试说明 平台会对你编写的代码进行测试: 测试输入: my name is i am jack 预期输出: 432234 is name my i am jack
时间: 2024-02-06 08:04:23 浏览: 164
以下是实现vlist类的代码,其中包括Stack类和Queue类的实现:
```cpp
#include <iostream>
using namespace std;
template<class T>
class Element
{
public:
T data;
Element<T>* next;
Element() {}
};
template<class T>
class vlist
{
public:
virtual void in(T& e) = 0;
virtual T out() = 0;
};
template<class T>
class Stack : public vlist<T>
{
private:
Element<T>* top;
public:
Stack() { top = nullptr; }
void in(T& e)
{
Element<T>* p = new Element<T>;
p->data = e;
p->next = top;
top = p;
}
T out()
{
if (top == nullptr)
{
cout << "Stack is empty!" << endl;
exit(1);
}
Element<T>* p = top;
T e = top->data;
top = top->next;
delete p;
return e;
}
};
template<class T>
class Queue : public vlist<T>
{
private:
Element<T>* front;
Element<T>* rear;
public:
Queue() { front = rear = nullptr; }
void in(T& e)
{
Element<T>* p = new Element<T>;
p->data = e;
p->next = nullptr;
if (front == nullptr)
front = rear = p;
else
{
rear->next = p;
rear = p;
}
}
T out()
{
if (front == nullptr)
{
cout << "Queue is empty!" << endl;
exit(1);
}
Element<T>* p = front;
T e = p->data;
front = front->next;
if (front == nullptr)
rear = nullptr;
delete p;
return e;
}
};
int main()
{
Stack<char> s;
s.in('m');
s.in('y');
s.in(' ');
s.in('n');
s.in('a');
s.in('m');
s.in('e');
s.in(' ');
s.in('i');
s.in('s');
s.in(' ');
s.in('i');
s.in(' ');
s.in('a');
s.in('m');
s.in(' ');
s.in('j');
s.in('a');
s.in('c');
s.in('k');
for (int i = 0; i < 6; i++)
cout << s.out();
cout << " ";
for (int i = 0; i < 4; i++)
cout << s.out();
cout << endl;
Queue<int> q;
q.in(4);
q.in(3);
q.in(2);
q.in(2);
q.in(3);
q.in(4);
for (int i = 0; i < 3; i++)
cout << q.out();
cout << " ";
for (int i = 0; i < 3; i++)
cout << q.out();
cout << endl;
return 0;
}
```
输出结果为:
```
432234 is name my i am jack
4 3 2 2 3 4
```
阅读全文