1.栈的顺序存储表示
#define QElemType int
#define Queue_Size 100
typedef struct {
QElemType data[Queue_Size];
int front, rear;
}SeqQueue;
2.顺序栈的基本操作
/// <summary>
/// initialize the seqstack
/// </summary>
/// <param name="S">is a seqstack</param>
void InitStack(SeqStack* S)
{
S->top = -1;
}
/// <summary>
/// make the seqstack empty
/// </summary>
/// <param name="S">is a seqstack</param>
void ClearStack(SeqStack* S)
{
S->top = -1;
}
/// <summary>
/// judge if the stack is empty or not
/// </summary>
/// <param name="S">is a stack</param>
/// <returns>1 is empty, and 0 is not.</returns>
int IsEmpty(SeqStack* S)
{
return (S->top == -1) ? 1 : 0;
}
/// <summary>
/// judge if the stack is full or not
/// </summary>
/// <param name="S">is a stack</param>
/// <returns>1 is full, and 0 is not</returns>
int IsFull(SeqStack* S)
{
return (S->top == Stack_Size - 1) ? 1 : 0;
}
/// <summary>
/// push a data in a stack
/// </summary>
/// <param name="S">is a stack</param>
/// <param name="e">is a data you want to push</param>
/// <returns>0 is fail, and 1 is success</returns>
int Push(SeqStack* S,SElemType e)
{
if (S->top == Stack_Size - 1)return 0;
else {
S->top++;
S->data[S->top] = e;
return 1;
}
}
/// <summary>
/// pop the data out
/// </summary>
/// <param name="S">is a stack</param>
/// <param name="e">the data you will poped out</param>
/// <returns>1 is success, and 0 is fail</returns>
int Pop(SeqStack* S, SElemType* e)
{
if (S->top == -1)return 0;
else {
*e = S->data[S->top];
S->top--;
return 1;
}
}
/// <summary>
/// get the top data of stack,but not pop out
/// </summary>
/// <param name="S">is a stack</param>
/// <param name="e">the data you want to get</param>
/// <returns>1 is success, and 0 is fail</returns>
int GetTop(SeqStack* S, SElemType* e)
{
if (S->top == -1)return 0;
else {
*e = S->data[S->top];
return 1;
}
}
3.主函数及验证
通过括号匹配的问题的综合函数来验证,例如:“ (] ”括号不匹配,“ {[()]} ”括号匹配。
#include<stdio.h>
void InitStack(SeqStack* S);
void ClearStack(SeqStack* S);
int IsEmpty(SeqStack* S);
int IsFull(SeqStack* S);
int Push(SeqStack* S,SElemType e);
int Pop(SeqStack* S, SElemType* e);
int GetTop(SeqStack* S, SElemType* e);
void BracketCheck(SeqStack* S);
int main(void)
{
SeqStack s, * ptrs = &s;
InitStack(ptrs);
BracketCheck(ptrs);
return 0;
}
/// <summary>
/// check if you have enter right bracked ,such as "()","[]","{}".
/// </summary>
/// <param name="S">is a stack whick is empty</param>
void BracketCheck(SeqStack* S)
{
if (!IsEmpty(S)) return;
SElemType ch, temp;
printf("Enter some bracked\n");
scanf("%c",&ch);
while (ch!='\n') {
if (ch == '(' || ch == '[' || ch == '{')Push(S, ch);
else {
GetTop(S, &temp);
if ((temp == '(' && ch == ')')|| (temp == '[' && ch == ']')|| (temp == '{' && ch == '}'))
Pop(S, &temp);
else if(ch==')'||ch==']'||ch=='}')
Push(S, ch);
}
scanf("%c", &ch);
}
if (IsEmpty(S))printf("Your brackedcheck is right\n");
else printf("Your brackedcheck is not right\n");
}