1.Linked Stacks
A linked stack uses a linked list to store the data in the stack.
template <class Datatype>
class LStack : public DLinkedList<Datatype>
{
public:
};
The head of the list points to the bottom of the stack, and the tail of the list points to the top of the stack.
[Push & Pop & Top] places a new item at the top of the stack;pop an item off the top of the stack.
void Push(Datatype p_data)
{
Append(p_data);
}
void Pop()
{
RemoveTail();
}
void Top()
{
return m_tail->m_data;
}
// The top func will not work correctly if the stack is empty.Be careful and make sure that the stack //is not empty before you call this function.
int Count()
{
return m_count;
}
2.Arrayed Stacks
It is of a fixed size, but you can use the array's Resize function to make it bigger or smaller as you desire.
template <class Datatype>
class AStack : public Array<Datatype>
{
public:
int m_top; // point to the next empty cell
};
[Cons]
AStack(int p_size) : Array<Datatype>(p_size)
{
m_top = 0;
}
declare a instance:
AStack<int> stack(10);
[Push & Pop & Top]
bool Push(Datatype p_data)
{
if (m_size != m_top)
{
m_array[m_top] = p_data;
m_top ++;
return true;
}
return false;
}
void Pop()
{
if (m_top > 0) m_top --;
}
Datatype Top()
{
return m_array[m_top - 1];
}
int Count()
{
return m_top;
}
3.Linked Queues
template <class Datatype>
class LQueue : public DLinkedList<Datatype>
{
public:
void Enqueue(Datatype p_data)
{
Append(p_data);
}
void Dequeue()
{
RemoveHead();
}
Datatype& Front()
{
return m_head->m_data;
}
};
4.Arrayed Queues
For a circular queue, you need 2 new vars: the index of the front of the queue and the number of items within the queue.
template <class Datatype>
class AQueue : public Array<Datatype>
{
public:
int m_front;
int m_count;
};
[Cons & Enqueue]
AQueue(int p_size) : Array<Datatype>(p_size)
{
m_front = 0;
m_count = 0;
}
bool Enqueue(Datatype p_data)
{
if (m_size != m_count)
{
m_array[(m_count + m_front) % m_size] = p_data;
m_count ++;
return true;
}
return false;
}
void Dequeue()
{
if (m_count > 0)
{
m_count --;
m_front ++;
if (m_front == m_size)
m_front = 0;
}
}
Datatype Front()
{
return m_array[m_front];
}
Datatype& operator [] (int p_index)
{
return m_array[(p_index + m_front) % m_size];
}