/*双端队列的简要实现
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
struct Node;
struct LinkQueue;
typedef struct Node* PtrToNode;
typedef struct LinkQueue* PtrToQueue;
typedef PtrToNode QNode;
typedef PtrToNode QueuePtr;
typedef PtrToQueue Queue;
typedef int ElementType;
struct Node{
ElementType data;
QNode Previous;
QNode Next;
};
struct LinkQueue{
QueuePtr front;
QueuePtr rear;
};
Queue InitQueue();/*初始化队列*/
void Push(Queue Q, ElementType e);/*插入前端*/
int Pop(Queue Q);/*前端出列*/
void Inject(Queue Q, ElementType e);/*插入后端*/
int Eject(Queue Q);/*后端出列*/
void QueueTraverse(Queue Q);/*遍历队列*/
/*初始化队列*/
Queue InitQueue(){
Queue Q = malloc(sizeof(struct LinkQueue));
if (Q == NULL)
return NULL;
Q->front = malloc(sizeof(struct Node));
Q->rear = malloc(sizeof(struct Node));
Q->front->Next = Q->rear;
Q->front->Previous = NULL;
Q->rear->Previous = Q->front;
Q->rear->Next = NULL;
return Q;
}
/*插入前端*/
void Push(Queue Q, ElementType e){
QueuePtr front = Q->front;//得到前端结点
QueuePtr Tmp = malloc(sizeof(struct Node));
if (Tmp == NULL)
return NULL;
Tmp->data = e;//赋值数据域
Tmp->Previous = front;
Tmp->Next = front->Next;
front->Next->Previous = Tmp;
front->Next = Tmp;
}
/*前端出列*/
int Pop(Queue Q){
QueuePtr head = Q->front->Next;//前端第一个结点
int data = head->data;
Q->front->Next = head->Next;
head->Next->Previous = Q->front;
free(head);
return data;
}
/*插入后端*/
void Inject(Queue Q, ElementType e){
QueuePtr rear = Q->rear;//得到尾端结点
QueuePtr Tmp = malloc(sizeof(struct Node));
if (Tmp == NULL)
return NULL;
Tmp->data = e;//赋值数据域
Tmp->Previous = rear->Previous;
Tmp->Next = rear;
rear->Previous->Next = Tmp;
rear->Previous = Tmp;
}
/*后端出列*/
int Eject(Queue Q){
QueuePtr head = Q->rear->Previous;//后端第一个结点
int data = head->data;
Q->rear->Previous = head->Previous;
head->Previous->Next = Q->rear;
free(head);
return data;
}
/*遍历队列*/
void QueueTraverse(Queue Q){
QueuePtr P = Q->front->Next;
while (P != NULL && P != Q->rear){
printf("%d ", P->data);
P = P->Next;
}
}
void main(){
Queue Q;
Q = InitQueue();
printf("\n前端插入:\n");
for (int i = 1; i <= 10; i++){
Push(Q, i);
}
QueueTraverse(Q);
printf("\n后端插入:\n");
for (int i = 11; i <= 20; i++){
Inject(Q, i);
}
QueueTraverse(Q);
printf("\n前端出列:\n");
for (int i = 1; i <= 5; i++){
Pop(Q);
}
QueueTraverse(Q);
printf("\n后端出列:\n");
for (int i = 1; i <= 5; i++){
Eject(Q);
}
QueueTraverse(Q);
}
双端队列简要实现
最新推荐文章于 2024-07-03 15:26:54 发布