一、栈的相关概念与特点
栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。
特点:
(1)集合性。栈是由若干个元素集合而成,当没有元素的空集合称为空栈;
(2)线性结构。除栈底元素和栈顶元素外,栈中任一元素均有唯一的前驱元素和后继元素;
(3)受限制的运算。只允许在栈顶实施压入或弹出操作,且栈顶位置由栈指针所指示;
(4)数学性质。当多个编号元素依某种顺序压入,且可任意时刻弹出时,所获得的编号元素排列的数目,恰好满足卡塔南数列的计算,即:
Cn=Cn2n/(n+1)
其中,n为编号元素的个数,Cn是可能的排列数目。
二、栈的代码实现
1.创建结构体
typedef struct Stack{
int top;
int data[MAXSIZE];
}*StackPtr;
2.初始化栈
int StackInit(){
StackPtr resultPtr = (StackPtr)malloc(sizeof(struct Stack)) ;
resultPtr->top = -1;
return resultPtr;
}
3.输出栈的内容
void outputStack(StackPtr paraStack){
int i;
for(i=0;i<=paraStack->top;i++)
{
printf("%d ",paraStack->data[i]);
}
printf("\n");
}
4.向栈中添加元素(压栈 / 入栈)
void push(StackPtr paraStackPtr,int paraValue){
//判断栈堆是否已满
if(paraStackPtr->top >= MAXSIZE-1)
{
printf("空间已满,不能推送元素!\n");
return;
}
//更新栈顶
paraStackPtr->top++;
//压入元素
paraStackPtr->data[paraStackPtr->top] = paraValue;
}
5.从栈中弹出元素(出栈)
int pop(StackPtr paraStackPtr){
//判断栈堆是否为空
if(paraStackPtr->top<0)
{
printf("栈堆为空,无法弹出元素!\n");
return;
}
//更新栈顶
paraStackPtr->top--;
//弹出元素
return paraStackPtr->data[paraStackPtr->top+1];
}
6.验证功能函数
void pushpopTest(){
printf("-------测试开始-------\n");
StackPtr tempStack = StackInit();
;
printf("创建空栈成功!\n");
printf("初始化后,栈堆是:");
outputStack(tempStack);
int i;
for(i=0;i<=10;i++)
{
printf("Pushing %d.\n", i);
push(tempStack, i);
outputStack(tempStack);
}
int j;
for (j = 0; j <= 11; j ++)
{
printf("Pop %d.\n", j);
pop(tempStack);
outputStack(tempStack);
}
printf("-------测试结束-------\n");
}
三、括号匹配的实现
括号匹配实际上就是对栈的一种运用,通过与先前压栈所输入的符号进行比对,判断是否匹配。
代码实现
bool bracketMatching(char* paraString, int paraLength) {
// 初始化,将#放入栈底
StackPtr tempStack = StackInit();
push(tempStack, '#');
char tempChar, tempPopedChar;
int i;
for (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;
}
break;
case ']':
tempPopedChar = pop(tempStack);
if (tempPopedChar != '[')
{
return false;
}
break;
case '}':
tempPopedChar = pop(tempStack);
if (tempPopedChar != '{')
{
return false;
}
break;
default:
break;
}
}
tempPopedChar = pop(tempStack);
if (tempPopedChar != '#')
{
return false;
}
return true;
}
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 = "()(])7*8+9[(()])";
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);
}
四、完整代码实现
#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 poped 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");
// Initialize.
CharStackPtr tempStack = charStackInit();
printf("After initialization, the stack is: ");
outputStack(tempStack);
// Pop.
for (char 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 true;
} // 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.
*/
void main() {
// pushPopTest();
bracketMatchingTest();
}// Of main
五、感悟
个人认为,栈的相关运用远不止于此。但是在本篇的示例中我们可以感受到栈的先入后出性对于逻辑性匹配具有很强的指向性作用,以一种简单的方式为正确的匹配带来了可能,具体的深度运用还需要我下来更加积极的探索
本文详细介绍了栈的基本概念、特点,包括其线性结构和受限运算,并通过C语言实现了栈的初始化、输出、压栈和弹栈等操作。此外,还展示了如何利用栈进行括号匹配的检查,以及提供了一组测试用例。栈的先入后出特性在逻辑匹配问题中展现出强大功能。
5419

被折叠的 条评论
为什么被折叠?



