Data.Structures.For.Game.Programmers.PART2.Basics.7.Stacks&Queues

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];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值