队列

队列

一种操作受限的线性表,只允许在表的一端进行插入,而在表的另一端进行删除.

队列的顺序存储结构

void InitQueue(SqQueue &s){
    s.rear = s.front = 0;
}
bool IsEmpty(SqQueue s){
    if(s.front == s.rear){
        return true;
    }
    return false;
}
bool EnQueue(SqQueue &s, ElemType e){
    if((s.rear + 1) % MaxSize == s.front) 
        return false;
    s.data[s.rear] = e;
    s.rear = (s.rear + 1) % MaxSize;
    return true;
}
bool DeQueue(SqQueue &s, ElemType &e){
    if(s.front == s.rear){
        return false;
    }
    e = s.data[s.front];
    s.front = (s.front + 1) % MaxSize;
    return true;
}

队列的链式存储结构

#define ElemType char
typedef struct LinkNode
{
    ElemType data;
    LinkNode *next;
} LinkNode;
typedef struct LinkQueue
{
    LinkNode *front;
    LinkNode *rear;
};


void InitQueue(LinkQueue &Q){
    Q.front = Q.rear = new LinkNode;
    Q.rear->next = NULL;
}
bool IsEmpty(LinkQueue Q){
    if(Q.rear == Q.front){
        return true;
    } else {
        return false;
    }
}
bool EnQueue(LinkQueue &Q, ElemType e){
    LinkNode *tmp = new LinkNode;
    tmp->data = e;
    tmp->next = NULL;
    Q.rear->next = tmp;
    Q.rear = tmp;
}
bool DeQueue(LinkQueue &Q, ElemType &e){
    if(Q.rear == Q.front) return false;
    LinkNode *tmp = Q.front->next;
    e = tmp->data;
    Q.front->next = tmp->next;
    if(tmp == Q.rear){
        Q.rear = Q.front;
    }
    delete(tmp);
    return true;
}

问题

问题一 : Q是一个队列, S是一个空栈, 实现将队列中的元素逆置.

#include <iostream>
#include <stdio.h>
#include <stack>
#include <queue>
using namespace std;


void Converse(queue<char> &q){
    stack<char> s;
    while(!q.empty()){
        s.push(q.front());
        q.pop();
    }
    while(!s.empty()){
        q.push(s.top());
        s.pop();
    }
}

int main(){
    queue<char> q;
    int n;
    while((n = getchar()) != EOF){
        q.push(n);
    }
    Converse(q);
    while(!q.empty()){
        cout << q.front();
        q.pop();
    }
    cout << endl;
}

问题二 :利用两个栈S1, S2来模拟一个队列, 实现队列的出队, 入队, 判空三个操作.

/* 判空 */
int QueueEmpty(Stack S1, Stack S2){
	if(StackEmpty(S1) && StackEmpty(S2)){
		return 1;
	} else {
		return 0
	}
}

/* 出队 */
void DeQueue(Stack &S1, Stack &S2, ElemType &e){
	if(!StackEmpty(S2)){
		Pop(S2, x);
	} else if(StackEmpty(S1)){
		printf("队列为空\n");
	} else {
		while(!StackEmpty(S1)){
			Pop(S1, x);
			Push(S2, x);
		}
		Pop(S2, x);
	}
}
/* 入队 */
int EnQueue(Stack &S1, Stack &S2, ElemType e){
	if(!StackOverflow(S1)){
		Push(S1, e);
		return 1;
	}
	if(StackOverflow(S1) && !StackEmpty(S2)){
		printf("队列满\n");
		return 0;
	}
	if(StackOverflow(S1) && StackEmpty(S2)){
		while(!StackEmpty(S1)){
			Pop(S1, x);
			Push(S2, x);
		}
	}
	Push(S1, e);
	return 1;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值