算法入门经典之栈和队列篇
算法,栈,数据结构,队列,ACM2016-07-17
做对的事情比把事情做对重要
/**
*@author StormMaybin
*@Date 2016-07-17
*/
最近一段时间会对数据结构的知识和算法基础进行总结,尽量一天一更!如果时间错不开的话,第二天会补上。
数据结构中,栈和队列是最基础的也是简单的,一种是先进后出的线性数据结构,另外一种是先进先出的线性数据结构!
# include <stdio.h>
const int MAXN = 50;
int queue[MAXN] = {0};
int main (void)
{
int n, front, rear;
scanf ("%d",&n);
for (int i = 0; i < n; i++)
{
queue[i] = i + 1;
}
front = 0;
rear = n;
while (front < rear)
{
printf ("%d ", queue[front++]);
queue[rear++] = queue[front++];
}
return 0;
}
运行结果:
单看这个程序的输出结果,没有任何错误,答案就是我们想要的,现在让我们看看rear的值到最后是多大?
rear 的值是14,恰好是7的2倍,这么看的话,每次数组要开到2n,这就极大的浪费了内存空间。
让我们用c++的STL队列来解决这个问题。
# include <cstdio>
# include <queue>
using namespace std;
queue <int> q;
int main (void)
{
int n;
scanf ("%d", &n);
for (int i = 0; i < n; i++)
{
//初始化队列
q.push(i+1);
}
while (! q.empty())
{
//打印队首元素
printf ("%d ", q.front());
//抛弃首元素
q.pop();
//把队首元素加到队尾
q.push(q.front());
//抛弃队首元素
q.pop();
}
return 0;
}
代码依旧简单,可读性也增强了不少!对于c++的STL库,不了解的可以去查查资料。
分析:中转站C的规则其实就是栈这个数据结果的特点!
/**
*@author StormMaybin
*@Date 2016-07-17
*/
# include <stdio.h>
const int MAXN = 1000 + 10;
int n, target[MAXN];
int main (void)
{
while (scanf("%d",&n) == 1)
{
int stack[MAXN];
int top = 0;
int A = 1;
int B = 1;
for (int i = 1; i <= n; i++)
{
scanf ("%d", &target[i]);
}
int ok = 1;
while (B <= n)
{
if (A == target[B])
{
A++;
B++;
}
else if (top && stack[top] == target[B])
{
top--;
B++;
}
else if (A <= n)
{
stack[++top] = A++;
}
else
{
ok = 0;
break;
}
}
printf ("%s\n",ok ? "Yes" : "No");
}
return 0;
}
打印结果
代码原理也很简单,输出结果是Yes只有两种情况,一种是正序,一种就是逆序!
接着,用c++STL库来写:
/**
*@author StormMaybin
*@Date 2016-07-17
*/
# include <cstdio>
# include <stack>
using namespace std;
const int MAXN = 1000 + 10;
int n;
int target [MAXN];
int main (void)
{
while (scanf ("%d",&n) == 1)
{
stack<int> s;
int A = 1;
int B = 1;
for (int i = 1; i <= n; i++)
{
scanf ("%d", &target[i]);
}
int ok = 1;
while (B <= n)
{
if (A == target[B])
{
A++;
B++;
}
else if (! s.empty() && s.top() == target[B])
{
s.pop();
B++;
}
else if (A <= n)
{
s.push(A++);
}
else
{
ok = 0;
break;
}
}
printf("%s\n", ok ? "Yes" : "No");
}
return 0;
}