双端队列:
即具备栈的特性(后进先出),又具备队列的特性(先进先出),可以在头尾分别进出 notice:
双端队列,可以在队列的头,入队列出队列,也可以在队列的尾入队列出队列
循环队列只能在尾部入队列,从头部出队列
原队列:
—— ——— ——— —— ——— ——— ——— ———
a1 a2 a3 a4 a5
—— ——— ——— —— ——— ——— ——— ———
↑_h ↑_t
头部进队列:
—— ——— ——— —— ——— ——— ——— ———
a6 a1 a2 a3 a4 a5
—— ——— ——— —— ——— ——— ——— ———
↑_h ↑_t
head = (head - 1 + SIZE) % SIZE
头部出队列:
—— ——— ——— —— ——— ——— ——— ———
a2 a3 a4 a5
—— ——— ——— —— ——— ——— ——— ———
↑_h ↑_t
head = (head + 1) % SIZE
尾部出队列:
—— ——— ——— —— ——— ——— ——— ———
a1 a2 a3 a4
—— ——— ——— —— ——— ——— ——— ———
↑_h ↑_t
tail = (tail - 1 + SIZE) % SIZE
尾部入队列:
—— ——— ——— —— ——— ——— ——— ———
a1 a2 a3 a4 a5 a6
—— ——— ——— —— ——— ——— ——— ———
↑_h ↑_t
tail = (tail + 1) % SIZE
队列为空
head == tail
队列为满
(tail + 1) % SIZE == head
双端队列判断回文:头部尾部同时出队列
a b c d e d c b a
↑_h_out ↑_t_out
判断头端出队列和尾端出队列的元素是否相等
b c d e d c b
↑_h_out ↑_t_out
---> a == a
结果
e
↑_h_out
↑_t_out
#include <iostream>
#include <cstring>
#define SIZE 512
using namespace std;
char queue[SIZE];
int head = 0, tail = 0;
void tail_inqueue(char c);
char tail_outqueue();
void head_inqueue(char c);
char head_outqueue();
int isempty();
int isfull(void);
int is_palindrom(char *pt);
int main(void)
{
char str[100];
cout << "双端队列判断回文输入:abcdedcba" << endl;
cin >> str;
if(is_palindrom(str))
cout << "是回文" << endl;
else
cout << "不是回文" << endl;
return 0;
}
// 尾部入队列:
void tail_inqueue(char c)
{
// 把数据放到尾部位置,尾部指针后移一格
queue[tail] = c;
// 考虑到循环队列
tail = (tail + 1) % SIZE;
cout << "tail_in = " << tail << endl;
}
// 尾部出队列:
char tail_outqueue()
{
// tail指向空所以减一
tail = (tail - 1 + SIZE) % SIZE;
cout << "tail_out = " << tail << endl;
return queue[tail];
}
// 头部入队列
void head_inqueue(char c)
{
head = (head - 1 + SIZE) % SIZE;
queue[head] = c;
cout << "head_in = " << tail << endl;
}
// 头部出队列
char head_outqueue()
{
// 头指针指向的元素弹出后,头指针指向下一个元素
char ch;
ch = queue[head];
head = (head + 1) % SIZE;
cout << "hea_outd = " << head << endl;
return ch;
}
// 判断队列是否为空,头指针==尾指针
int isempty()
{
return head == tail;
}
// 判断队列是否为满,若为满返回1
int isfull(void)
{
return (tail+1) % SIZE == head;
}
int is_palindrom(char *pt)
{
// 把字符串压入队列
int i, len;
len = strlen(pt);
char c1,c2;
for(i = 0; i < len; i++)
{
// 队列不满则入队列
if(!isfull())
tail_inqueue(pt[i]);
}
while(!isempty())
{
// 队列不空则出队列
c1 = head_outqueue();
if(!isempty())
c2 = tail_outqueue();
else
break;
if(c1 == c2)
continue;
else
return 0;
}
// 若队列空则是回文
return 1;
}
/*
双端队列判断回文输入:abcdedcba
abcdedcba
tail_in = 1
tail_in = 2
tail_in = 3
tail_in = 4
tail_in = 5
tail_in = 6
tail_in = 7
tail_in = 8
tail_in = 9
hea_outd = 1
tail_out = 8
hea_outd = 2
tail_out = 7
hea_outd = 3
tail_out = 6
hea_outd = 4
tail_out = 5
hea_outd = 5
是回文
*/