資料結構隊列

來源:互聯網
上載者:User

#include <iostream>
#include <assert.h>
using namespace std;
/*
struct Node
{
 int info;
 Node *next;
};

struct queuelk
{
 struct Node *front;
 struct Node *back;
};

void init_queue(struct queuelk* q)
{
 q->back = q->front = NULL;
}

void queue_is_empty(struct queuelk *q)
{
 if(q->front==NULL)
 {
  return;
 }
}

void enqueue(struct queuelk *q, int info)
{
 struct Node *temp = NULL;
 temp = (Node*)malloc(sizeof(Node));
 assert(temp!=NULL);
 if(q->front == NULL)     //這是隊列的第一個結點
 {
  q->front = q->back = temp;
  temp->info = info;
  return;
 }
 q->back->next = temp;
 temp->info = info;
 q->back = temp;
}

bool dequeue(struct queuelk *q, int *info)
{
 if(q->front == NULL)
 {
  return false;
 }
 *info = q->front->info;
 if(q->front == q->back)
 {
  free(q->front);
  q->front = q->back = NULL;
  return true;
 }
 q->front = q->front->next;
 return true;
}
*/

//這是個通用隊列.

//寫一個迴圈隊列.
//

static int arr[100];
static int size = 100;

struct queuelk
{

 int rear;
 int size;
};

void init_queue(struct queuelk *q)
{
 q->front = -1;       //這個-1很重要
 q->rear = -1;
}

bool enqueue(struct queuelk *q, int info)
{  
 if(q->front == 0 && q->rear+1 == 100 || q->rear+1 == q->rear)
 {
   return false;
 }
 q->rear = (q->rear==100)? 0 : ++q->rear;
 if(q->front == -1)         //第一個元素.
 {
   q->front = 0;         //追上了才算是隊列滿.
 }
  arr[q->rear] = info;       //每次在隊尾入隊,分析一下用什麼條件判斷隊滿..什麼條件呢
  return true;
}

bool dequeue(struct queuelk *q, int *info)
{
  if(q->front == -1)
  {
   return false;
  }
  *info = arr[q->front];
  if(q->front == q->rear)
  {
   q->front = q->rear =-1;      //結束標記在哪種資料結構裡都很重要..
  }
  else
  {
   q->front = (q->front== 100) ? 0 : ++q->front;
   
  }
  return true;
}

聯繫我們

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