当前位置: 代码迷 >> 综合 >> 线性数据结构—队列
  详细解决方案

线性数据结构—队列

热度:85   发布时间:2024-01-29 03:39:48.0

队列的顺序储存实现

通常采用循环队列实现,front和rear指针的移动采用“加1取余”法来体现“循环”

写代码时会发现一个问题,队列空满的判断条件是怎么样的?

由于采用了取余的思路,最终会导致队列空满时 front和rear均相对,最终无法通过rear与front来判断队列空满状态。

为什么会出现这样的情况?

大小为n的数组实现的队列中可以存放的数据状态有n+1种(0->n),但是rear front所能描述的状态最多只能由n种

解决方案:

1)使用额外标记:Size或者tag域

2)仅使用n-1个数组空间(下面的代码即是这样处理的)

 

struct QNode{ElementType Data[MaxSize];int rear;int front;
}; 
typedef struct QNode *Queue;void AddQ(Queue p,ElementType item)
{if((p->rear+1)%MaxSize==p->front){cout<<"队列满";return ;}p->rear=(p->rear+1)%MaxSize;  //循环队列的实现 p->Data[p->rear]=item;
}ElementType DeleteQ(Queue p)
{if(p->front==p->rear){cout<<"队列空";return -1; }else{p->front=(p->front+1)%MaxSize;return p->Data[p->front];}
} 

 

队列的链式存储实现 

 

struct Node {ElementType Data;struct Node* Next;
};struct QNode { //链队列结构struct Node* rear; //指向队尾结点struct Node* front;//指向队头结点
};typedef struct QNode* Queue;ElementType DeleteQ(Queue p)
{struct Node* FrontCell;ElementType Front;if (p->front == NULL) {cout << "队列空"; return ERROR;}FrontCell = p->front;if (p->front == p->rear)         //!若队列只有一个元素p->front = p->rear = NULL;   //删除后队!列置为空else p->front = p->front->Next;Front = FrontCell->Data;delete FrontCell;   //释放被删除节点的空间return Front;
}void AddQ(Queue p, ElementType item)
{struct Node * np;np=new struct Node;np->Data = item;if (p->rear == NULL)  p->front=p->rear = np; //若队列为空else p->rear=p->rear->Next = np;
}Queue CreateQueue()
{Queue q = new struct QNode;q->front = NULL;q->rear = NULL;return q;
}bool IsEmpty(Queue p)
{if (p->front == NULL) return true;return false;
}