数据结构之队列

  1 //C++实现链队
  2 #include <iostream>
  3 using namespace std;
  4 struct Node
  5 {
  6   int data;
  7   Node *next;
  8 };
  9 class LinkQueue
 10 {
 11 public:
 12   LinkQueue();
 13   ~LinkQueue();
 14   void EnQueue(int x);//入队操作
 15   int DeQueue();//出队操作,队头元素出队
 16   int GetQueue();//取队头元素
 17   int Empty();//判空
 18 private:
 19   Node *front, *rear;//队头和队尾指针,分别指向头结点和终端结点
 20 };
 21 LinkQueue::LinkQueue()
 22 {
 23   Node *s = NULL;
 24   s = new Node;//创建头结点s
 25   s->next = NULL;
 26   front = rear = s;//将队头指针和队尾指针都指向头结点s
 27 }
 28 LinkQueue::~LinkQueue()
 29 {
 30   Node *q = NULL;
 31   while (front!=NULL) // 释放单链表的每一个结点的存储空间
 32   {
 33     q = front;
 34     front = front->next;
 35     delete q;
 36   }
 37   q = NULL;
 38 }
 39 void LinkQueue::EnQueue(int x)
 40 {
 41   Node *s = NULL;
 42   s = new Node;
 43   s->data = x;
 44   s->next=NULL;
 45   rear->next = s;
 46   rear = s;
 47 }
 48 int LinkQueue::DeQueue()
 49 {
 50   int x;
 51   Node *p = NULL;
 52   if (rear==front)
 53   {
 54     cout<<"下溢";
 55   }
 56   p = front->next;
 57   x = p->data;
 58   front->next = p->next;
 59   if (p->next==NULL)//判断出队前队列长度是否为1
 60   {
 61     rear = front;
 62   }
 63   delete p;
 64   p = NULL;
 65   return x;
 66 }
 67 int LinkQueue::GetQueue()
 68 {
 69   if (front==rear)
 70   {
 71     cout<<"下溢异常";
 72   }
 73   else
 74   {
 75     return front->next->data;
 76   }
 77 }
 78 int LinkQueue::Empty()
 79 {
 80   if (front==rear)
 81   {
 82     return 1;
 83   }
 84   else
 85   {
 86     return 0;
 87   }
 88 }
 89 int main()
 90 {
 91   int x=0;
 92   LinkQueue Q;
 93   Q.EnQueue(1);
 94   Q.EnQueue(2);
 95   cout << "队头元素为" << Q.GetQueue() << endl;
 96   x = Q.DeQueue();
 97   cout << "执行一次出队操作,出队元素是:" << x << endl;
 98   if (Q.Empty() == 1) cout << "队列为空" << endl;
 99   else cout << "队列非空" << endl;
100   return 0;
101 }

 

posted @ 2020-11-22 09:41  丁帅帅dss  阅读(61)  评论(0)    收藏  举报