栈的基础操作:
#include <iostream>
#include <algorithm>
#include <string>
#include <stack>
#include <cstring>
using namespace std;
const int maxnsize=100;
typedef struct Stack
{
int* data;
int top;
int maxnsize;
}SqStack;
void InitStack(SqStack &s, int n)
{
s.data = new int [n];
s.top = -1;
s.maxnsize = n;
}
bool StackEmpty(SqStack &s)
{
if(s.top == -1)
return true;
return false;
}
bool Push(SqStack &s, int x)
{
if(s.top == s.maxnsize-1)
return false;
s.data[++s.top] = x;
return true;
}
bool Pop(SqStack &s, int &x)
{
if(s.top == -1)
return false;
x = s.data[s.top--];
return true;
}
bool GetTop(SqStack &s, int &x)
{
if(s.top == -1)
return false;
x = s.data[s.top];
return true;
}
///3.2)编写算法,判定所给的操作序列是否合法,合法返回true
int The_three_problem(char c[])
{
///两个点,出栈操作是否合法。终态是否为空.
int i=0;
int p=0, q=0;
while(c[i] != '\0')
{
if(c[i] == 'I')
{
p++;
}
else if(c[i] == 'O')
{
q++;
}
if(q>p)
return 0;
i++;
}
cout<<p<<" "<<q<<endl;
if(p != q)
return -1;
return 1;
}
int main()
{
ios::sync_with_stdio(false);
//char a[] = {'I', 'O', 'I', 'I', 'O', 'I', 'O', 'O'};
//char b[] = {'I', 'O', 'O', 'I', 'O', 'I', 'I', 'O'};
//char c[] = {'I', 'I', 'I', 'O', 'I', 'O', 'I', 'O'};
char d[] = {'I', 'I', 'I', 'O', 'O', 'I', 'O', 'O'};
// cout<<The_three_problem(a)<<endl;
//cout<<The_three_problem(b)<<endl;
// cout<<The_three_problem(c)<<endl;
cout<<The_three_problem(d)<<endl;
return 0;
}
两个栈共享存储空间,进栈出栈代码如下(王道第五题):
#include <iostream>
#include <algorithm>
#include <string>
#include <stack>
#include <cstring>
using namespace std;
const int maxnsize=100;
typedef struct Stack
{
int data[maxnsize];
int top[2];
}Stk;
void InitStack(Stk &s)
{
s.top[0] = -1;
s.top[1] = maxnsize;
}
int push(Stk &s, int i, int x)
{
if(i<0 || i>1)
return 0;
if(s.top[1] - s.top[0] == 1)
return 0;
switch(i){
case 0:s.data[++s.top[0]] = x;break;
case 1:s.data[--s.top[1]] = x;break;
}
return 1;
}
int Pop(Stk &s, int i, int &x)
{
if(i<0 || i>1)
return 0;
switch(i)
{
case 0:
if(s.top[0] == -1)
return 0;
x = s.data[s.top[0]--];
break;
case 1:
if(s.top[2] == maxnsize)
return 0;
x = s.data[s.top[1]++];
break;
}
return 1;
}
int main()
{
ios::sync_with_stdio(false);
return 0;
}