//双向链表模拟队列
#include <iostream>
#include <queue>
using namespace std;
queue<int>my_queue;
class Node
{
public:
int element;
Node* pre;
Node* next;
Node()
{
pre = nullptr;
next = nullptr;
}
};
class Listnode
{
public:
Node* listnode;
Node* rear;
int count = 0;
Listnode();
void En_listnode(int x);
void De_listnode(int x);
void Print_max();
bool Is_empty();
void Print_listnode();
};
Listnode::Listnode()
{
count = 0;
listnode = new Node;
listnode->next = nullptr;
listnode->pre = nullptr;
}
bool Listnode::Is_empty()
{
if (count == 0)
{
return true;
}
else
return false;
}
void Listnode::En_listnode(int x)
{
if (Is_empty()==true)
{
Node* ptr = new Node;
ptr->element = x;
ptr->pre = listnode;
listnode->next = ptr;
rear = ptr;
count++;
return;
}
else
{
Node* temp = new Node;
temp->pre = rear;
temp->element = x;
rear->next = temp;
temp->next = nullptr;
while (x > rear->element)
{
temp->pre = rear->pre;
rear->pre->next = temp;
delete rear;
rear = temp;
}
rear = temp;
temp = nullptr;
return;
}
}
void Listnode::De_listnode(int x)
{
if (listnode->next->element == x)
{
Node* temp = listnode->next;
listnode->next = listnode->next->next;
listnode->next->pre = listnode;
delete temp;
return;
}
}
void Listnode:: Print_max()
{
cout << "这个窗口最大的数是" << listnode->next->element << endl;
}
void Listnode::Print_listnode()
{
Node* ptr = listnode->next;
while (ptr)
{
cout << ptr->element << " ";
ptr = ptr->next;
}
cout << endl;
}
int main()
{
Listnode my_listnode;
int arr[100];
cout << "请问窗口大小为多少" << endl;
int window_size = 0;
cin >> window_size;
cout << "请问一共输入多少个数据" << endl;
int data_size;
cin >> data_size;
cout << "开始输入数据" << endl;
for (int i = 0; i < data_size; i++)
{
cin >> arr[i];
}
int time = data_size - window_size;
cout << "一共移动" << time << "次" << endl;
for (int i = 0; i < window_size; i++)
{
my_queue.push(arr[i]);
my_listnode.En_listnode(arr[i]);
}
my_listnode.Print_max();
for (int i = window_size; i < time+window_size; i++)
{
my_queue.push(arr[i]);
int temp = my_queue.front();//此时出列的元素
my_queue.pop();
my_listnode.En_listnode(arr[i]);
my_listnode.De_listnode(temp);
my_listnode.Print_max();
}
return 0;
}
算法复杂度 比每次滑动都重新判断一次要简单,这也是优势之一,但是代码量较多