鏈式隊列的實現

來源:互聯網
上載者:User

 這今天,要做一個AIS解析的東西,需要用到隊列資料結構,於是乎就自己寫了一個測試了一下,現在給大家奉獻出來!

 

代碼在附件裡面。

 

#include <stdio.h>
#include<stdlib.h>
#define MAX_SIZE 50
typedef struct QNode
{
 int data;    //資料域
 struct QNode *next;  //指向下一個元素
}QNode,*QueuePtr;

typedef struct
{
 QueuePtr front;   //隊列頭指標
 QueuePtr rear;   //隊列尾指標
 int length;    //隊列的長度
}LinkQueue;

//構造一個空隊列
void InitQueue(LinkQueue &Q)
{
 Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
 if (!Q.front)
 {
  exit(1);
 }
 Q.front->next = NULL;
 Q.length = 0;
 return;
}

//銷毀隊列
void DestroyQueue(LinkQueue &Q)
{
 while (Q.front)
 {
  Q.rear = Q.front->next;
  if (Q.front)
  {
   free(Q.front);
  }
  Q.front = Q.rear;
 }
 Q.length = 0;
}

//插入元素,入隊列
void EnQueue(LinkQueue &Q,int e)
{
 if (Q.length == MAX_SIZE)
 {
  printf("隊列已經滿了!不能插入元素!");
 }
 else
 {
  QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
  if (!p)
  {
   exit(1);
  }
  p->data = e;
  p->next = NULL;
  
  Q.rear->next = p; //指向新插入的節點
  Q.rear = p;    
     Q.length ++;  //元素個數加1
 } 
}

//出隊列,從隊列頭出來
void DeQueue(LinkQueue *Q,int e)
{
 //隊列是空的,不能刪除
 if (Q->front == Q->rear)
 {
  printf("隊列已經為空白,不能刪除!");
 }

 else
 {
  QueuePtr p = Q->front->next; //取出隊列頭
  e = p->data;
  Q->front->next = p->next;  //刪除節點p
  Q->length --;     //元素個數減1
  
  //如果隊列只有一個元素
  if (Q->rear == p)
  {
   Q->rear = Q->front;
  }
  if (p != NULL)
  {
   free(p);
   p = NULL;
  }
 }
}

//求隊列長度
int GetLength(LinkQueue *Q)
{
 return Q->length;
}

//取隊列的頭元素
int GetHead(LinkQueue *Q)
{
 if (0 == Q->length)
 {
  printf("隊列為空白!\n");
 }
 else
 {
  return Q->front->next->data;
 }
}

//取隊列的尾元素
int GetTail(LinkQueue *Q)
{
 if (0 == Q->length)
 {
  printf("隊列為空白!\n");
 }
 else
 {
  return Q->rear->data;
 }
}
void main()

 LinkQueue Q;
 InitQueue(Q);
 EnQueue(Q,1);
 EnQueue(Q,2);
 EnQueue(Q,3);
 //DeQueue(&Q,0);

 int len = GetLength(&Q);
 printf("隊列總共有幾個元素:%d,%d,%d\n",len,GetHead(&Q),GetTail(&Q));
 int daxiao = sizeof(QNode);
}

 

 

 

程式的運行結果如下:

隊列總共有幾個元素:3,1,3
Press any key to continue

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.