根据给出的入栈顺序1,2,3,4....
以及栈的容量
然后给出几个待测试的序列比如
int a[7]={1,2,3,4,5,6,7};
int b[7]={3,2,1,7,5,6,4};
int c[7]={7,6,5,4,3,2,1};
int d[7]={5,6,4,3,7,2,1};
int e[7]={1,7,6,5,4,3,2};//这里为了方便测试,不再一一给出数据
算法的思想是,对栈在入栈的过程中,当入栈元素恰好等于待出栈元素,那么就让他出栈,同时把出栈序列当前等待元素后移一位,循环最后判断标志位和栈是否为空,本题使用链栈
# include <stdio.h>
# include <malloc.h>
typedef struct node
{
int data;
struct node* next;
}Node,*Pnode;
typedef struct stu
{
Pnode base;
Pnode top,bottom;
}Base,*Pbase;
bool isempty(Pbase S);
void init(Pbase S);
void push(Pbase S,int val);
void pop (Pbase S,int* val);
void bianli(Pbase S);
int size(Pbase S);
int gettop(Pbase S);
void test(Pbase S,int* a,int T1,int T2);
int main()
{
int val=0;
Base S;
init (&S);
//int a[5][7]={1,2,3,4,5,6,7,3,2,1,7,5,6,4,7,6,5,4,3,2,1,5,6,4,3,7,2,1,1,7,6,5,4,3,2};
int a[7]={1,2,3,4,5,6,7};
int b[7]={3,2,1,7,5,6,4};
int c[7]={7,6,5,4,3,2,1};
int d[7]={5,6,4,3,7,2,1};
int e[7]={1,7,6,5,4,3,2};
test(&S,a,5,7);
return 0;
}
void init(Pbase S)
{
S->base=(Pnode)malloc(sizeof(Node));
S->bottom=S->base;
S->top=S->base;
}
void push(Pbase S,int val)
{
Pnode pnew=(Pnode)malloc(sizeof(Node));
pnew->data=val;
pnew->next=S->top;
S->top=pnew;
}
void pop (Pbase S,int* val)
{
if(!isempty(S))
{
*val=S->top->data;
Pnode r=S->top;
S->top=S->top->next;
free(r);
}
}
bool isempty(Pbase S)
{
if(S->bottom==S->top)
return true;
else return false;
}
void bianli(Pbase S)
{
Pnode L=S->top;
while(L!=S->bottom)
{
printf("%d ",L->data);
L=L->next;
}
printf("\n");
}
int size(Pbase S)
{
int i=0;
Pnode L=S->top;
while(L!=S->base)
{
i++;
L=L->next;
}
return i;
}
int gettop(Pbase S)
{
return S->top->data;
}
void test(Pbase S,int* a,int T1,int T2)
{
int val;
int flag=true;
while(!isempty(S))
pop(S,&val);
int current=0;
for(int i=1;i<=T2;i++)
{
push(S,i);
if(size(S)>T1)
{
flag=false;
break;
}
while(!isempty(S) && gettop(S)==a[current])//反复出栈 匹配
{
pop(S,&val);
current++;
}
}
if(isempty(S)==true && flag==true)//不为空且标志位正确
{
printf ("OK\n");
}
else printf("NO\n");
}