0
最近我觉得,随着基本的数据结构,如栈和队列,一个新的数据结构应该只存储最后n个给定的值。新数据结构
我给它起了名字TUBE。
这将有三个基本操作 -
top() // returns the element on the top
void push(element) // push element into the tube
void pop() //deletes the top element in the tube
For example if i have created a tube of size 4
initial - []
push(2) - [2]
push(3) - [3,2]
push(4) - [4,3,2]
push(5) - [5,4,3,2]
push(6) - [6,5,4,3]
push(7) - [7,6,5,4]
push(8) - [8,7,6,5]
pop - [7,6,5]
pop - [6,5]
我觉得这可能是非常有用的,在做的过程中,我们需要记住一些我们所访问的前一个元素。
template<class T>
class tube
{
T *val;
int size;
int front,rear;
public:
tube(int k)
{
val=new T[k];
size=k;
front=rear=-1;
}
T top()
{
if (front!=-1)
return val[front];
else
return NULL;
}
void push(T k)
{
front=(front+1)%size;
if (rear==-1)
rear=0;
else if (front == rear)
rear=(rear+1)%size;
val[front]=k;
}
void pop()
{
if (front == -1)
abort();
else if (front == rear)
front=rear=-1;
else
{
front--;
if (front<0)
front=size-1;
}
}
};
请分享您对这方面的看法,并提出改进建议,将不胜感激。
你能举个例子在何处,这可能有实际用途? –
属于http://codereview.stackexchange.com? –
看起来像一个固定长度的队列,推出最后一个项目。 – Oded