簡體   English   中英

使用堆棧來確定表達式是否具有平衡的括號

[英]Using a stack to determine if an expression has balanced parentheses

我正在完成本學期的上學作業,並且是第一次被引入堆棧,但是我的程序存在問題,無法正確分析表達式。 一切都執行,但是程序總是以表達式不平衡的結果出現。 有什么線索可以指示我正確的方向嗎?

//    
//  main.cpp
//  Balanced Parenthesis
#include "StringStack.h"
#include <iostream>
using namespace std;


int main ()
{
StringStack stack;
char entry;
    int parCounter = 0;
cout << "This program will accept a string and determine whether it has balanced        parenthesis.\n";
cout << "Please type a sentence to be analyzed\n";

while (cin.get (entry) && entry != '\n')
{
            stack.push(entry);

}
if (stack.isEmpty()) {
    cout << "The stack is empty./n";
}

else{
    stack.pop(entry);
    if (entry == ')') {
        parCounter++;
    }
    else if(entry == '('){
        parCounter--;
    }


}
if (parCounter > 0 || parCounter < 0){
            cout << "This expression has UNBALANCED parentheses\n";
        }
        else
        {
            cout << "This expression has BALANCED parentheses\n";

    }



return 0;
}

//  StringStack.h
//  Balanced Par

#include <iostream>
using namespace std;

#ifndef StringStack_h
#define StringStack_h


//Define our stack class and its contents
class StringStack
{
private:

    char *stackArray;
    int stackSize;
    char top;
public:
StringStack();
    ~StringStack() {delete[] stackArray;}
    void push(char);
    void pop(char &);
    bool isBalanced();
    bool isEmpty();
};

#endif

//Constructor
StringStack::StringStack()
{
    stackArray = new char[stackSize];
    top = 0;
}

//Function to determine if stack is empty.
bool StringStack::isEmpty()
{
    if (top == 0)
        return true;
    else
        return false;
}

//Function to push letters/puncuation onto the stack
void StringStack::push(char letter)
{
//if (isEmpty())
{
    top++;
    stackArray[top] = letter;
}
//else
//{
    //exit(1);
//}
}

//Function to pop letters/puncuation off the stack
void StringStack::pop(char &letter)
{
if (isEmpty())
{
    cout << "The stack is empty.\n";
    exit(1);
}
else
{
    letter = stackArray[top];
    top--;
}
}

您沒有在任何地方初始化或設置成員stackSize 這使得new char[stackSize]未定義行為,並且可能發生任何事情。

解決此問題后,您只需檢查堆棧的頂部 您需要圍繞parCount進行循環-控制if在堆棧為空之前運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM