Answers for "stack in data structure using cpp"

C++
0

stack data structure c++

/*
 * Complete the 'isBalanced' function below.
 *
 * The function is expected to return a STRING.
 * The function accepts STRING s as parameter.
 */
 
string isBalanced(string s) {
    stack<char> c;
    for(int i=0;i<s.length();i++)
    {
        if(s[i]=='('||s[i]=='{'||s[i]=='[')
        {
            c.push(s[i]);
        }
        if(!c.empty())
        {
            if(s[i]==')')
            {
                if(c.top()=='(')
                {
                   c.pop();
                   continue;
                }else
                {
                    break;
                }
            }
            //
             if(s[i]=='}')
            {
                if(c.top()=='{')
                {
                   c.pop();
                   continue;
                }else
                {
                    break;
                }
            }
            //
             if(s[i]==']')
            {
                if(c.top()=='[')
                {
                   c.pop();
                   continue;
                }else
                {
                    break;
                }
            }
        }else
        {
            return "NO";
        }
    }
    return c.empty()? "YES":"NO";

}
Posted by: Guest on January-01-2022
0

stack implementation using class in c++

#include<iostream>
using namespace std;
#define Size 5

class Stack
{
private:
	int Array[Size];
	int top;
public:
	Stack()
	{
		top = -1;
	}
	void Push(int x)
	{
		if (top == Size - 1)
		{
			cout << "Error, stack overFlow!" << endl;
			return;
		}

		Array[++top] = x;
	}
	void Pop()
	{
		if (top == -1)
		{
			cout << "Error, stack is Empty!" << endl;
			return;
		}
		top--;
	}

	int Top()
	{
		return Array[top];
	}
	bool IsEmpty()
	{
		if (top == -1)
			return 1;
		return 0;
	}
	void print()
	{
		cout << "Stack: ";
		for (int i = 0; i <= top; i++)
		{
			cout << Array[i] << " ";
		}
		cout << "n";
	}

};
int main()
{
	Stack s;
	s.Push(1);
	s.Push(2);
	s.print();

	return 0;
}
Posted by: Guest on December-23-2021

Code answers related to "stack in data structure using cpp"

Browse Popular Code Answers by Language