一个经典的栈结构练习题,输入一连串括号,匹配不同括号左右是否匹配。e.g.{【】()}是匹配的,而{(】】则因缺少相应的右括号不匹配。《C语言程序设计现代方法》第十章 编程题大题1
#include<stdio.h>
#include <string.h>
char* push(char cha, char* ptr);
char* pop(char* ptr);
int main()
{
int i = 0;
char braces[240];
char stack[240] = {0};
char *top;
scanf("%s",braces);
top = &stack[0];
top = push (braces[i], top);
i ++; // push the first one
for (;i < strlen(braces); i ++) { // fhuntion to push and estimate the bracket
if (braces[i] == '}'){
if (*top == '{'){ // if bracket is matche then del the matched one
top = pop(top);
}
}
else if (braces[i] == ']'){
if (*top == '['){
top = pop(top);
}
}
else if (braces[i] == ')'){
if (*top == '('){
top = pop(top);
}
}
else { // if not matche, push
top = push (braces[i], top);
}
}
if (top == &stack[0]) // if the pointer is in the bottom the stack is empty
puts("matche");
else
puts("not matche");
return 0;
}
char* push(char cha, char* ptr)
{
ptr ++;
*(ptr) = cha;
return ptr; //pointer go up and save the element on the top
}
char* pop(char* ptr)
{
ptr --;
return ptr; //pointer go down stack will ignore the previous element
}
附加一个 逆波兰算法 的代码,也用到了栈结构,逆波兰算法是一种非常贴合栈结构的算式语法。i.e.在读入句子过程中一旦取得算符就依算符处理前两个数字然后将得到的数字放在栈顶。
#include<stdio.h>
#include <string.h>
#include <ctype.h>
int* add(int* ptr);
int* sub(int* ptr);
int* pro(int* ptr);
int* div(int* ptr);
int* push(char cha, int* ptr);
int main()
{
int i = 0;
char expr[] = "612345+-**/3+";
int stack[240] = {0};
char *top;
top = &stack[0];
top = push (expr[i], top);
i ++;
for (;i < strlen(expr); i ++){
if (expr[i] == '+')
top = add(top);
else if (expr[i] == '-')
top = sub(top);
else if (expr[i] == '*')
top = pro(top);
else if (expr[i] == '/')
top = div(top);
else if (isdigit)
top = push (expr[i], top);
else
break;
}
printf("result : %d",*top);
return 0;
}
int* push(char cha, int* ptr)
{
ptr ++;
*(ptr) = cha - '0';
return ptr;
}
int* add(int* ptr)
{
int i,j;
i = *ptr;
ptr --;
j = *ptr;
j = j + i;
*ptr = j;
return ptr;
}
int* sub(int* ptr)
{
int i,j;
i = *ptr;
ptr --;
j = *ptr;
j = i - j;
*ptr = j;
return ptr;
}
int* pro(int* ptr)
{
int i,j;
i = *ptr;
ptr --;
j = *ptr;
j = i * j;
*ptr = j;
return ptr;
}
int* div(int* ptr)
{
int i,j;
i = *ptr;
ptr --;
j = *ptr;
j = i / j;
*ptr = j;
return ptr;
}