数据结构之栈的应用 -- 括号匹配(C语言)
一、栈的定义栈作为一种数据结构 ,是一种只能在一端进行插入和删除操作的特殊线性表 。它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数据被第一个读出来)。二、代码功能1、定义栈2、栈的初始化3、输出栈4、放入元素5、删除元素6、测试放入和删除元素7、判断括号匹配8、测试括号匹配9、代码入口10、运行结果三、栈——括号匹配的代码1、
·
一、栈的定义
栈作为一种数据结构 ,是一种只能在一端进行插入和删除操作的特殊线性表 。它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数据被第一个读出来)。
二、代码功能
1、定义栈
2、栈的初始化
3、输出栈
4、放入元素
5、删除元素
6、测试放入和删除元素
7、判断括号匹配
8、测试括号匹配
9、代码入口
10、运行结果
三、栈——括号匹配的代码
1、定义栈
typedef struct CharStack {
int top;
int data[STACK_MAX_SIZE]; //The maximum length is fixed.
} *CharStackPtr;
2、栈的初始化
CharStackPtr charStackInit()
{
CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(struct CharStack));
resultPtr->top = -1;
}
3、输出栈
void outputStack(CharStackPtr paraStack)
{
for(int i = 0; i <= paraStack->top; i ++)
{
printf("%c ", paraStack->data[i]);
}
printf("\r\n");
}
4、放入元素
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;
}
5、删除元素
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];
}
6、测试放入和删除元素
void pushPopTest()
{
char ch;
printf("---- pushPopTest begins. ----\r\n");
// 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");
}
7、判断括号匹配
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;
}
8、测试括号匹配
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);
}
9、代码入口
int main()
{
pushPopTest();
bracketMatchingTest();
}
10、运行结果
---- pushPopTest begins. ----
After initialization, the stack is:
Pushing a.
a
Pushing b.
a b
Pushing c.
a b c
Pushing d.
a b c d
Pushing e.
a b c d e
Pushing f.
a b c d e f
Pushing g.
a b c d e f g
Pushing h.
a b c d e f g h
Pushing i.
a b c d e f g h i
Pushing j.
a b c d e f g h i j
Pushing k.
Cannot push element: stack full.
a b c d e f g h i j
Pushing l.
Cannot push element: stack full.
a b c d e f g h i j
Pop j.
a b c d e f g h i
Pop i.
a b c d e f g h
Pop h.
a b c d e f g
---- pushPopTest ends. ----
Is the expression '[2 + (1 - 3)] * 4' bracket matching? 1
Is the expression '( ) )' bracket matching? 0
Is the expression '()()(())' bracket matching? 1
Is the expression '({}[])' bracket matching? 1
Is the expression ')(' bracket matching? 0
四、整体代码
#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];
} *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()
{
char ch;
printf("---- pushPopTest begins. ----\r\n");
// 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 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.
*/
int main()
{
pushPopTest();
bracketMatchingTest();
}
五、总结
栈主要可以利用数组的相关理念来帮助理解,其中最重要的是对栈顶的注意,该代码较核心和最难的部分就是判断括号匹配的代码。

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)