STL实现
通过应用STL中的stack
实现:
应用介绍:
.pop
弹出栈顶元素
.top()
返回栈顶元素
.empty()
询问栈是否为空
.push()
向栈顶插入一个元素
#include<iostream>
#include<stack>
using namespace std;
stack<char> A;//STL 栈
bool bracketMatching(char* paraString, int paraLength)
{
for (int i = 0; i < paraLength; i++)
{
if (paraString[i] == '(' || paraString[i] == '[' || paraString[i] == '{')
{
A.push(paraString[i]);//左括号就入栈 push
}
else if (paraString[i] != '('&& paraString[i] != '['&¶String[i] !='{' && paraString[i] != ')' && paraString[i] != ']' && paraString[i] != '}')
{
continue;//不是括号就跳过
}
else
{
if (A.empty())//如果是右括号,而此时栈为空
{
//说明括号不匹配,返回0
return 0;
}
else if (paraString[i] == ')' && A.top() != '(')//如果是右括号,并且没有与之匹配的左括号在栈顶
{
//说明括号也不匹配,返回0
return 0;
}
else if (paraString[i] == '}' && A.top() != '{')
{
//说明括号也不匹配,返回0
return 0;
}
else if (paraString[i] == ']' && A.top() != '[')
{
return 0;
}
else//能匹配,一但左括号被匹配,就出栈。
A.pop();
}
}
//最后看栈是否为空:
if (A.empty())//所有都应该被匹配了,最后栈应该为空
return 1;//为空说明所有都能匹配,输出1
else
return 0;//不为空说明还有括号没有被匹配,输出0
}
void bracketMatchingTest()
{
char* tempExpression = "[2 + (1 - 3)] * 4";
bool tempMatch = bracketMatching(tempExpression, 17);
printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
tempExpression = "( ) )";
tempMatch = bracketMatching(tempExpression, 6);
printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
tempExpression = "()()(())";
tempMatch = bracketMatching(tempExpression, 8);
printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
tempExpression = "({}[])";
tempMatch = bracketMatching(tempExpression, 6);
printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
tempExpression = ")(";
tempMatch = bracketMatching(tempExpression, 2);
printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
}// Of bracketMatchingTest
/**
The entrance.
*/
int main()
{
// pushPopTest();
bracketMatchingTest();
}// Of main
线性表实现
#include <stdio.h>
#include <malloc.h>
#define STACK_MAX_SIZE 10
/**
* Linear stack of integers. The key is data.
*/
typedef struct CharStack
{
int top;
int data[STACK_MAX_SIZE]; //The maximum length is fixed.
} *CharStackPtr;
/**
* Output the stack.
*/
void outputStack(CharStackPtr paraStack)
{
for (int i = 0; i <= paraStack->top; i++)
{
printf("%c ", paraStack->data[i]);
}// Of for i
printf("\r\n");
}// Of outputStack
/**
* Initialize an empty char stack. No error checking for this function.
* @param paraStackPtr The pointer to the stack. It must be a pointer to change the stack.
* @param paraValues An int array storing all elements.
*/
CharStackPtr charStackInit()
{
CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(struct CharStack));
resultPtr->top = -1;
return resultPtr;
}//Of charStackInit
/**
* Push an element to the stack.
* @param paraValue The value to be pushed.
*/
void push(CharStackPtr paraStackPtr, int paraValue)
{
// Step 1. Space check.
if (paraStackPtr->top >= STACK_MAX_SIZE - 1)
{
printf("Cannot push element: stack full.\r\n");
return;
}//Of if
// Step 2. Update the top.
paraStackPtr->top++;
// Step 3. Push element.
paraStackPtr->data[paraStackPtr->top] = paraValue;
}// Of push
/**
* Pop an element from the stack.
* @return The popped value.
*/
char pop(CharStackPtr paraStackPtr)
{
// Step 1. Space check.
if (paraStackPtr->top < 0)
{
printf("Cannot pop element: stack empty.\r\n");
return '\0';
}//Of if
// Step 2. Update the top.
paraStackPtr->top--;
// Step 3. Push element.
return paraStackPtr->data[paraStackPtr->top + 1];
}// Of pop
/**
* Test the push function.
*/
void pushPopTest()
{
printf("---- pushPopTest begins. ----\r\n");
char ch;
// Initialize.
CharStackPtr tempStack = charStackInit();
printf("After initialization, the stack is: ");
outputStack(tempStack);
// Pop.
for (ch = 'a'; ch < 'm'; ch++)
{
printf("Pushing %c.\r\n", ch);
push(tempStack, ch);
outputStack(tempStack);
}//Of for i
// Pop.
for (int i = 0; i < 3; i++)
{
ch = pop(tempStack);
printf("Pop %c.\r\n", ch);
outputStack(tempStack);
}//Of for i
printf("---- pushPopTest ends. ----\r\n");
}// Of pushPopTest
/**
* Is the bracket matching?
*
* @param paraString The given expression.
* @return Match or not.
*/
bool bracketMatching(char* paraString, int paraLength)
{
// Step 1. Initialize the stack through pushing a '#' at the bottom.
CharStackPtr tempStack = charStackInit();
push(tempStack, '#');
char tempChar, tempPopedChar;
// Step 2. Process the string.
for (int i = 0; i < paraLength; i++)
{
tempChar = paraString[i];
switch (tempChar)
{
case '(':
case '[':
case '{':
push(tempStack, tempChar);
break;
case ')':
tempPopedChar = pop(tempStack);
if (tempPopedChar != '(')
{
return false;
} // Of if
break;
case ']':
tempPopedChar = pop(tempStack);
if (tempPopedChar != '[')
{
return false;
} // Of if
break;
case '}':
tempPopedChar = pop(tempStack);
if (tempPopedChar != '{')
{
return false;
} // Of if
break;
default:
// Do nothing.
break;
}// Of switch
} // Of for i
tempPopedChar = pop(tempStack);
if (tempPopedChar != '#')
{
return false;
} // Of if
return true;
}// Of bracketMatching
/**
* Unit test.
*/
void bracketMatchingTest()
{
char* tempExpression = "[2 + (1 - 3)] * 4";
bool tempMatch = bracketMatching(tempExpression, 17);
printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
tempExpression = "( ) )";
tempMatch = bracketMatching(tempExpression, 6);
printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
tempExpression = "()()(())";
tempMatch = bracketMatching(tempExpression, 8);
printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
tempExpression = "({}[])";
tempMatch = bracketMatching(tempExpression, 6);
printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
tempExpression = ")(";
tempMatch = bracketMatching(tempExpression, 2);
printf("Is the expression '%s' bracket matching? %d \r\n", tempExpression, tempMatch);
}// Of bracketMatchingTest
/**
The entrance.
*/
int main()
{
// pushPopTest();
bracketMatchingTest();
}// Of main
分析
输出栈中的元素
void outputStack(CharStackPtr paraStack)
{
for (int i = 0; i <= paraStack->top; i++)
{
printf("%c ", paraStack->data[i]);
}// Of for i
printf("\r\n");
}// Of outputStack
初始化栈
CharStackPtr charStackInit()
{
CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(struct CharStack));
resultPtr->top = -1;
return resultPtr;
}//Of charStackInit
用malloc为栈分配一块空间,并将栈顶指向为-1
入栈
void push(CharStackPtr paraStackPtr, int paraValue)
{
// Step 1. Space check.
if (paraStackPtr->top >= STACK_MAX_SIZE - 1)
{
printf("Cannot push element: stack full.\r\n");
return;
}//Of if
// Step 2. Update the top.
paraStackPtr->top++;
// Step 3. Push element.
paraStackPtr->data[paraStackPtr->top] = paraValue;
}// Of push
如果栈顶所指向的位置大于了栈的大小,则栈溢出
否则就将栈顶的位置+1,再赋值
出栈
char pop(CharStackPtr paraStackPtr)
{
// Step 1. Space check.
if (paraStackPtr->top < 0)
{
printf("Cannot pop element: stack empty.\r\n");
return '\0';
}//Of if
// Step 2. Update the top.
paraStackPtr->top--;
// Step 3. Push element.
return paraStackPtr->data[paraStackPtr->top + 1];
}// Of pop
如果栈所指向的位置小于0,即为-1时,说明栈空,无法弹出了
出栈就是将栈顶的位置-1,返回操作之后栈顶元素的值
匹配
bool bracketMatching(char* paraString, int paraLength)
{
// Step 1. Initialize the stack through pushing a '#' at the bottom.
CharStackPtr tempStack = charStackInit();
push(tempStack, '#');
char tempChar, tempPopedChar;
// Step 2. Process the string.
for (int i = 0; i < paraLength; i++)
{
tempChar = paraString[i];
switch (tempChar) {
case '(':
case '[':
case '{':
push(tempStack, tempChar);
break;
case ')':
tempPopedChar = pop(tempStack);
if (tempPopedChar != '(') {
return false;
} // Of if
break;
case ']':
tempPopedChar = pop(tempStack);
if (tempPopedChar != '[') {
return false;
} // Of if
break;
case '}':
tempPopedChar = pop(tempStack);
if (tempPopedChar != '{') {
return false;
} // Of if
break;
default:
// Do nothing.
break;
}// Of switch
} // Of for i
tempPopedChar = pop(tempStack);
if (tempPopedChar != '#') {
return false;
} // Of if
return true;
}// Of bracketMatching
在栈底-1的位置存入‘#’,代表栈空
- 如果为左括号,就入栈;
- 如果为右括号,就拿出栈顶元素与之比较,如果不能与之匹配,就说明不能整个公式或括号字符串不能完成括号匹配。
- 最后如果栈不为空,说明还有未被匹配的括号,即
tempPopedChar != '#'
,就说明不能匹配
心得
注意栈的特点,先入的被压在底部,先入后出,后入先出
。
而括号匹配问题恰好能够运用这一特点。