用C++實現隊列的程式碼_C 語言

來源:互聯網
上載者:User
C++實現隊列,如有不足之處,還望指正
複製代碼 代碼如下:

// MyQueue.cpp : 定義控制台應用程式的進入點。
//實現鏈式隊列(queue),包括一個頭結點。隊列操作包括在隊頭出隊(pop)、在隊尾入隊(push)、
//取得隊頭元素(front_element)、取得隊尾元素(back_element)、隊列元素個數(size)、
//隊列是否為空白(empty)。
#include "stdafx.h"
#include <iostream>
using namespace std;
//定義隊列的節點結構
template <class T>
struct NODE
{
 NODE<T>* next;
 T data;
};
template <class T>
class MyQueue
{
public:
 MyQueue()
 {
  NODE<T>* p = new NODE<T>;
  if (NULL == p)
  {
   cout << "Failed to malloc the node." << endl;
  }
  p->data = NULL;
  p->next = NULL;
  front = p;
  rear = p;
 }
//在隊尾入隊
 void push(T e)
 {
  NODE<T>* p = new NODE<T>;
  if (NULL == p)
  {
   cout << "Failed to malloc the node." << endl;
  }
  p->data = e;
  p->next = NULL;
  rear->next = p;
  rear = p;
 }
//在隊頭出隊
 T pop()
 {
  T e;
  if (front == rear)
  {
   cout << "The queue is empty." << endl;
   return NULL;
  }
  else
  {
   NODE<T>* p = front->next;
   front->next = p->next;
   e = p->data;
   //注意判斷當只有一個元素,且刪除它之後,rear指向的node被刪除
   //應將其指向頭結點
   if (rear == p)
   {
    rear = front;
   }
   delete p; p = NULL;
   return e;
  }
 }
 //取得隊頭元素
 T front_element()
 {
  if (front == rear)
  {
   cout << "The queue is empty." << endl;
   return NULL;
  }
  else
  {
   NODE<T>* p = front->next;
   return p->data;
  }
 }
 T back_element()
 {
  if (front == rear)
  {
   cout << "The queue is empty." << endl;
   return NULL;
  }
  else
  {
   return rear->data;
  }
 }

 //取得隊列元素個數
 int size()
 {
  int count(0);
  NODE<T>* p = front;
  while (p != rear)
  {
   p = p->next;
   count++;
  }
  return count;
 }

 //判斷隊列是否為空白
 bool empty()
 {
  if (front == rear)
  {
   return true;
  }
  else
  {
   return false;
  }
 }
private:
 NODE<T>* front; //指向頭結點的指標。 front->next->data是隊頭第一個元素。
 NODE<T>* rear;//指向隊尾(最後添加的一個元素)的指標
};
int _tmain(int argc, _TCHAR* argv[])
{
 MyQueue<int> myqueue;
 cout << myqueue.size() << endl;
 myqueue.push(10);
 myqueue.push(20);
 myqueue.push(30);
 cout << myqueue.front_element() << endl;
 cout << myqueue.back_element() << endl;
 myqueue.pop();
 if (myqueue.empty())
 {
  cout << "The queue is empty now." << endl;
 }
 else
 {
  cout << "The queue has " << myqueue.size() << " elements now." << endl;
 }
 myqueue.pop();
 myqueue.pop();
 if (myqueue.empty())
 {
  cout << "The queue is empty now." << endl;
 }
 else
 {
  cout << "The queue has " << myqueue.size() << " elements now." << endl;
 }
 return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.