我通過堆棧做了一個括號檢查器程序。它將字符串作爲輸入,並檢查字符串或表達式是否等於no。開口和閉合的括號。如果是,它會打印「Paranthesis are balanced」。否則「Paranthesis不平衡」。但另一個非常奇怪,它只是打印一些隨機值,並沒有將表達式作爲輸入,只是單獨打印一些垃圾值。下面的代碼括號平衡器程序
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
// Structure defining Stack data structure
struct Stack {
int count;
char data[50];
} s;
/*
Initializes the count index to 0
*/
void initialize() {
s.count = 0;
}
/*
Checks if Stack is Full or not
*/
bool Is_Full() {
if(s.count > 50)
return true;
else
return false;
}
/*
Checks if Stack is Empty or not
*/
bool Is_Empty() {
if(s.count == 0){
return true;
}
else{
return false;
}
}
/*
Adds an element to stack and then increment count index
*/
bool push(int num) {
if (Is_Full())
return false;
else {
s.data[s.count + 1] = num;
s.count++;
return true;
}
}
/*
Removes count element from stack and decrement count index
*/
bool pop() {
if (Is_Empty())
return false;
else {
s.count = s.count - 1;
s.data[s.count+1];
}
return true;
}
int main(void) {
char expression[100];
int i, len;
initialize();
printf("Enter an expression \n");
printf("%s", &expression);
len = strlen(expression);
/*
# for '{' : we push '{' in stack
# for '}' : we pop a character from stack. For every '}' there must be one '{' earlier.
This will ensure that
** There are equal number of '{' and '}' characters in string.
** For every '{' there is a '}' in input string later.
*/
for(i = 0; i < len; i++){
if(expression[i] == '(' || expression[i] == '{' || expression[i] == '['){
push(expression[i]);
}
if(expression[i] == ')' || expression[i] == '}' || expression[i] == ']'){
pop();
}
}
if(Is_Empty()){
printf("Parenthesis are balanced\n");
}
else{
printf("Parenthesis are unbalanced\n");
}
return 0;
}
和這裏的輸出: -
沒有圖像的文字。將文字發佈爲文字!看[問],我們沒有調試服務。 – Olaf
'if(s.count> 50)'>'if(s.count> = 50)' –
您的代碼沒有意義。我建議打開編譯器警告,因爲一個好的編譯器可能會有很多關於's.data [s.count + 1];'的行;''''' – EOF