Answer to Question #236730 in C++ for Ahmad

Question #236730
Task 1:
Complete the body of this function. You do not need to check the precondition. You
may use the stack template class
bool balanced(const char p[ ], size_t n)
// Precondition: p[0]...p[n-1] contains n characters, each of which
// is '(', ')', '{' or '}'.
// Postcondition: The function returns true if the characters form a
// sequence of correctly balanced parentheses with each '(' matching
// a ')' and each '{' matching a '}'. Note that a sequence such as
// ( { ) } is NOT balanced because when we draw lines to match the
// parentheses to their partners, the lines cross each other. On the
// other hand, ( { } ) and { ( ) } are both balanced.
Task2:
Consider following Linked List:
struct Node {
int data;
Node *next;
class LList {
public:
LList();
~LList();
private:
Node *head;
int size;
};
LList::LList () {
head = NULL;
size = 0;
}
Implement the destructor LList::~LList ().
Note: You can use same linked list used in Task 1 and Task 2.
1
Expert's answer
2021-09-15T23:39:23-0400
bool balanced(string e)
{ 
    stack<char> st;
    char n;
    for (int i = 0; i < e.length(); i++)
    {
        if (e[i] == '(' || e[i] == '['
            || e[i] == '{')
        {
            st.push(e[i]);
            continue;
        }
        if (st.empty())
            return false;
 
        switch (e[i]) {
        case ')':
            n = st.top();
            st.pop();
            if (n == '{' || n == '[')
                return false;
            break;
 
        case '}':
            n = st.top();
            st.pop();
            if (n == '(' || n == '[')
                return false;
            break;
 
        case ']':
            n = st.top();
            st.pop();
            if (n == '(' || n == '{')
                return false;
            break;
        }
    }
    return (st.empty());
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS