描述:代码判断出栈顺序有没有可能
思路:
1.首先创建两个数组A、B、其中A用于存放输入的数据,B用于存放需要检测的数据 。
2.设置i,j控制数组A,B中元素位置。
3.将A数组的数据用while循环压入堆栈,并且与B数组的数据对比,如果数据相同且堆栈未满,
则弹出堆栈栈顶元素,并且B中j指向下一位置 。
4.当跳出循环时,如果堆栈为空,说明数据全部与数组B数据匹配,B顺序正确,否则不正确。
time:2019/8/21
author by LLQ
代码如下:
#include<stdio.h>
#include<malloc.h>
#include"stack.h"
bool StackOrder(int A[],int B[],stack *s){
if(A==NULL)
return false;
int i,j;
i=j=0;
while(i<5){
printf("插入数据\n");//用于检测
push(s,A[i++]);
while(!stackempty(s)&&B[j]==gettop(s)){
pop(s);
j++;
}
}
if(stackempty(s))
return true;
return false;
}
int main(){
// 初始化
stack s1,s2;
inistack(&s1);
inistack(&s2);
int A[5]={1,2,3,4,5};
int B[5]={3,2,1,5,4};//正确顺序,错误顺序:3,1,2,4,5
bool flag=0;
//判断函数
flag=StackOrder(A,B,&s1);
if(flag)
printf("顺序正确!");
else
printf("顺序错误!");
}
需要引入的stack.h文件
#include <stdio.h>
#include <malloc.h>
#include <string.h>
//******堆栈数据结构******
typedef struct
{
char *base;
char *top;
int size;
}stack;
//******堆初始化 ******
void inistack(stack *A)
{
A ->base =(char *)malloc(100*sizeof(char));
A ->top = A ->base;
A ->size = 100;
}
//******判断栈是否为空******
bool stackempty(stack *A)
{
if(A->top==A->base)
return true;
else
return false;
}
bool push(stack *A,char x)
{
if(A->top-A->base >=A ->size)
A->base = (char *)realloc(A ->base, (A->size+10)*sizeof(char));
*A->top++=x;
return true;
}
char pop(stack *A)
{
if(A->top==A->base )
return 0;
return(*--A->top);
}
char gettop(stack *A)
{
if(A->top==A->base)
return 0;
return *(A->top-1);
}