题目
in
11
1 1
1 2
1 3
1 4
1 5
3
2
2
2
2
2
out
1
2
3
4
5
1
2
3
4
5
-1
思路
单项栈的话实现reverse复杂度为O(n)
用个双向栈,reverse的时候直接把头尾指针互换,然后换个方向复杂度为O(1)大大减少用时
需要注意一下插入删除空斩时候的特殊情况,避免访问越界
代码
#include<iostream>
using namespace std;
struct dot
{
int data;
dot* prev = NULL;
dot* next = NULL;
};
struct stack
{
dot* head = NULL;
dot* tail = NULL;
bool reverse = false;
};
int main()
{
int z;
cin >> z;
stack s;
for(int i = 0; i < z; i++)
{
int c;
cin >> c;
switch(c)
{
case 1:
int n;
cin >> n;
if(s.reverse)
{
if(s.head == NULL)
{
s.head = s.tail = new dot;
s.head->data = n;
//栈首尾还是得NULL的
}
else
{
s.tail->next = new dot;
s.tail->next->prev = s.tail;
s.tail = s.tail->next;
s.tail->data = n;
}
cout << s.tail->data << endl;
}
else
{
if(s.tail == NULL)
{
s.tail = s.head = new dot;
s.tail->data = n;
}
else
{
s.head->prev = new dot;
s.head->prev->next = s.head;
s.head = s.head->prev;
s.head->data = n;
}
cout << s.head->data << endl;
}
break;
case 2:
if(s.reverse)
{
if(s.tail)
{
if(s.tail->prev)
{
dot* temp = s.tail;
s.tail->prev->next = s.tail->next;
s.tail = s.tail->prev;
delete temp;
cout << s.tail->data << endl;
}
else
{
dot* temp = s.tail;
s.tail = s.head = NULL;
delete temp;
cout << "-1" << endl;
}
}
else
cout << "-1" << endl;
}
else
{
if(s.head)
{
if(s.head->next)
{
dot* temp = s.head;
s.head->next->prev = s.head->prev;
s.head = s.head->next;
delete temp;
cout << s.head->data << endl;
}
else
{
dot*temp = s.head;
s.head = s.tail = NULL;
delete temp;
cout << "-1" << endl;
}
}
else
{
cout << "-1" << endl;
}
}
break;
case 3:
s.reverse = !s.reverse;
if(s.reverse)
if(s.tail)
cout << s.tail->data << endl;
else
cout << "-1" << endl;
else
if(s.head)
cout << s.head->data << endl;
else
cout << "-1" << endl;
break;
}
}
}