随手写的简单队列

昨晚一个偶然的机会,随手写了一段队列代码。很久没有写过data struct的代码,写出来后错漏百出。经过几番修改,应该可用了。

队列需要实现以下几个功能:

1. 删除给定节点;

2. 获取队列节点个数;

3. 获取队首节点。

代码如下:

class Queue
{
public:
 
 ///@brief 从队列链表中移除一个Elem
    void Remove(Elem* elem)
    { 
  if (elem == NULL)
  {
   ///TODO 出错处理
   return;
  }
  
  if (m_count == 1)
  {
   //队列只有一个元素
   m_head = NULL;
   m_tail = NULL;
  }
  else if (elem->GetNext() == NULL) /// 删除队尾元素
  {
   elem->GetPrev()->SetNext(NULL);
   m_tail = elem->GetPrev();
  }
  else if (elem->GetPrev() == NULL) /// 删除队首元素
  {
  elem->GetNext()->SetPrev(NULL);
   m_head = elem->GetNext();
  }
  else
  {
   elem->GetPrev()->SetNext(elem->GetNext());
   elem->GetNext()->SetPrev(elem->GetPrev());
  }
  
 elem->SetNext(NULL);
 elem->SetPrev(NULL);
  –m_count;
    }

    ///@brief 将Task放到队列尾
    void PushBack(Elem* elem)
    {
  if (elem == NULL)
  {
   ///TODO 出错处理
   return;
  }
  
  if (m_count == 0) ///队列为空
  {
   m_head = elem;
   m_tail = elem;
  }
  else
  {
   m_tail->SetNext(elem);
   elem->SetPrev(m_tail);
   m_tail = elem;
  }
  
  ++m_count;
    }

    ///@brief 返回指向队首Elem的指针,但不从队列中移除它
    Elem* GetFront() const
    {
        return m_head;
    }
 
 ///@brief 返回队列元素个数
 int GetCount() const
 {
  return m_count;
 }

private:
    Elem* m_head; /** 队头 */
    Elem* m_tail; /** 队尾 */
 int m_count; /** 保存队列元素个数 **/
};

Advertisements

About chill

不再执意欢喜反倒让人欢喜
This entry was posted in TECH. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s