栈:https://blog.csdn.net/weixin_41892460/article/details/82973851
CheckStack.h
#ifndef __CHECKSTACK_H__
#define __CHECKSTACK_H__
#include<stdio.h>
#include<stdlib.h>
#include <assert.h>
#include <malloc.h>
typedef int DataType;
typedef struct Stack
{
DataType* _a;
size_t _top;
size_t _capacity;
}Stack;
void StackInit(Stack* s);
void StackPush(Stack* s, DataType x);
void StackPop(Stack* s);
DataType StackTop(Stack* s);
size_t StackSize(Stack* s);
int StackEmpty(Stack* s);
void StackDestory(Stack* s);
int InOutStackIsValid(int* InOrder, int InSize, int* OutOrder, int OutSize);
void TestCheckStack();
#endif
CheckStack.c
#include "CheckStack.h"
void StackInit(Stack* s)
{
assert(s != NULL);
s->_a = (DataType*)malloc(sizeof(DataType)* 10);
s->_top = 0;
s->_capacity = 10;
}
void StackDestory(Stack* s)
{
assert(s);
s->_a = NULL;
s->_top = 0;
s->_capacity = 0;
free(s);
s = NULL;
}
void StackPush(Stack* s, DataType x)
{
DataType* cur;
assert(s);
if (s->_top == s->_capacity)
{
cur = (DataType*)realloc(s->_a, sizeof(s->_capacity) * 2);
if (cur != NULL)
{
s->_a = cur;
}
s->_capacity *= 2;
}
s->_a[s->_top++] = x;
}
void StackPop(Stack* s)
{
assert(s);
assert(s->_top > 0);
s->_top--;
}
//DataType StackTop(Stack* s)
//{
// assert(s);
// assert(s->_top > 0);
// return s->_a[s->_top - 1];
//
//}
DataType StackTop(Stack* s)
{
if (NULL == s)
{
printf("栈已空!!!");
return 0;
}
return s->_a[s->_top - 1];
}
size_t StackSize(Stack* s)
{
assert(s);
return s->_top++;
}
//int StackEmpty(Stack* s)
//{
// assert(s);
// return s->_top == 0 ? 0 : 1;
//}
int StackEmpty(Stack* s)
{
if (NULL == s)
{
return 0;
}
if (s->_top == 0)
{
return 0;
}
return 1;
}
Test.c
#include "CheckStack.h"
int InOutStackIsValid(int* InOrder, int InSize, int* OutOrder, int OutSize)
{
assert(InOrder&&OutOrder);
Stack s;
int In = 0;
int Out = 0;
if (InSize != OutSize)
return 0;
StackInit(&s);
while (Out < OutSize)
{
//栈顶元素与Outorder中的第一个元素不同就入栈
while (StackTop(&s) != OutOrder[Out] || StackEmpty(&s) == 0)
{
if (In < InSize)
StackPush(&s, InOrder[In++]);
else
return 0;
}
//栈顶元素和Outorder的第一个元素相同就出栈
StackPop(&s);
Out++;
}
return 1;
}
void TestCheckStack()
{
int InOrder[] = { 1, 2, 3, 4, 5 };
int InSize = sizeof(InOrder) / sizeof(InOrder[0]);
int OutOrder[] = { 5, 4, 3, 2, 1 };
int OutSize = sizeof(OutOrder) / sizeof(OutOrder[0]);
if (InOutStackIsValid(InOrder, InSize, OutOrder, OutSize))
{
printf("输出合法!!\n");
}
else
{
printf("输出不合法!!!\n");
}
}
int main()
{
TestCheckStack();
system("pause");
return 0;
}