判断出栈序列
题目如下
请判断:指定的序列能否仅由 入栈 和 出栈 操作得到。
输入:
有若干组数据输入
每组数据中,第一行为两个个整数 n 和 m。n 表示需要依次从 1~n 入栈,m 表示这组数据有 m 个出栈序列需要判断,当 n=0 且 m=0 时停止。
接下来有行,每行表示一个出栈序列输出:
对每一个出栈序列,如果能正常出栈,则输出 Yes,否则输出 No。sample:
input:
5 2
1 2 3 4 5
5 4 1 2 3
6 1
6 5 4 3 2 1
0 0output:
Yes
NoYes
摸摸鱼,顺便记录一点有用的东西。
一个 long
类型的简单的栈的代码,便于调试和交题目。
class mystack
{
private:
typedef struct node
{
int value;
struct node *next;
} node;
static node *makenode(int value)
{
node *ret = (node *)malloc(sizeof(node));
ret->value = value;
ret->next = nullptr;
return ret;
}
node *head;
public:
mystack()
{
this->head = mystack::makenode(-1);
}
void push(int value)
{
node *into = mystack::makenode(value);
into->next = this->head->next;
this->head->next = into;
}
void pop()
{
node *todel = this->head->next;
this->head->next = this->head->next->next;
free(todel);
}
int top()
{
return this->head->next->value;
}
bool empty()
{
if (this->head->next == nullptr)
return true;
else
return false;
}
};
这道题的一个坑点是如果再判断序列的过程中读一个判断一个的话,那么如果操作方式是发现不满足的序列元素立即返回 false
,那么需要适用循环把剩余的缓冲区元素读取掉,不然下一次输入就会有错误。
while (i++ < n - 1)
buffer = scanf("%*d");
Ω \Omega Ω