`
jaychang
  • 浏览: 716094 次
  • 性别: Icon_minigender_1
  • 来自: 嘉兴
社区版块
存档分类
最新评论

链式循环队列添加,删除,取首

 
阅读更多
#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;
}
 
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics