天天看點

鍊式循環隊列添加,删除,取首

#include<stdlib.h>
#include<iostream>

#define TRUE 1
#define FALSE 0

using namespace std;

typedef struct LinkQueueNode{
  char data;
  LinkQueueNode *next;
}LinkQueueNode;

typedef struct CycQueue{
  LinkQueueNode *front;
  LinkQueueNode *rear;
  int maxLength;
  int currentLength;
}CycQueue;

CycQueue *Q=(CycQueue*)malloc(sizeof(CycQueue));

int InitialCycQueue(CycQueue *Q)
{
  LinkQueueNode *QueueHead=   (LinkQueueNode*)malloc(sizeof(LinkQueueNode));
  if(QueueHead!=NULL){
    Q->front=QueueHead;
    Q->front->next=NULL;
    Q->rear=Q->front;
    cout<<"請輸入循環隊列的大小\n";
    cin>>Q->maxLength;
    Q->currentLength=0;
    return TRUE;
  }
  return FALSE;
}


//元素進入隊尾,隊尾指針指向新加入的元素
int EnterCycQueue(CycQueue *Q,char data)
{
  if(Q->currentLength==Q->maxLength){
    cout<<"隊列已經滿了\n";
    return FALSE;
  }
  LinkQueueNode *newNode=(LinkQueueNode*)malloc(sizeof(LinkQueueNode));
  if(newNode==NULL)return FALSE;
  newNode->data=data;
  Q->rear->next=newNode;
  Q->rear=newNode;
  Q->rear->next=Q->front;
  Q->currentLength++;
  return TRUE;
}

//隊首元素出隊
int QuitCycQueue(CycQueue *Q)
{
  if(Q->front==Q->rear)
  {
    cout<<"隊列為空\n";
    return FALSE;
  }
  LinkQueueNode *p=(LinkQueueNode*)malloc(sizeof(LinkQueueNode));
  if(p==NULL)return FALSE;
  p=Q->front->next;
  Q->front->next=p->next;
  Q->currentLength--;
  free(p);
}

//擷取隊首元素值
char GetCycHead(CycQueue *Q)
{
  if(Q->front==Q->rear){
    cout<<"隊列為空\n";
    return FALSE;
  }
  return Q->front->next->data;
}

//初始化隊列并添加隊列元素
void procInitial()
{
  char data;
  InitialCycQueue(Q);
  cout<<"輸入隊列元素,當輸入#時結束\n";
  cin>>data;
  while(data!='#')
  {
    if(EnterCycQueue(Q,data)==FALSE)return;
    //Q->currentLength++;
    cin>>data;  
   }
}

int main()
{
  procInitial();
  QuitCycQueue(Q);
  cout<<GetCycHead(Q)<<"\n";
  cout<<"目前隊列大小"<<Q->currentLength;
  return 0;
}
      

繼續閱讀