Question

Complete the following C program to solve the parenthesis matching problem using a stack. We studied...

Complete the following C program to solve the parenthesis matching problem using a stack. We studied the problem and the algorithm in class. Given a sequence of chars (symbols), check if each “(”, “{”, or “[” is paired with a matching “)”, “}”, or “[”. For example,

  1. correct: ( )(( )){([( )])}    
  2. correct: (( )(( ))){([( )])}  
  3. incorrect: )(( )){([( )])}    
  4. incorrect: ({[ ])}    
  5. incorrect: (  

#include <stdio.h>

#include <stdlib.h>

#define size 100

void push(char *s, int* top, char element);

char pop(char *s, int *top);

int full(int *top, const int size);

int empty(int *top);

void init(int *top);

void init(int *top)

{*top = 0;

}

void push(char *s, int* top, char element)

{s[(*top)++] = element;

}

char pop(char *s, int *top)

{return s[--(*top)];

}

int full(int *top, const int size)

{return *top == size ? 1 : 0;

}

int empty(int *top)

{return *top == 0 ? 1 : 0;

}

void main(){

int top;

char element;

char stack[size];

init(&top);

//You are required to complete the following:

//read a sequence of chars

//check if each parenthesis matches with the correct one; print error message if not.

//you can define variables and arrays that you need.

}

Homework Answers

Answer #1

CODE SNAPSHOTS:

OUTPUT SNAPSHOTS:

CODE:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 100

bool check(char *par, char *s, int *top);
void push(char *s, int *top, char element);
char pop(char *s, int *top);
int full(int *top, const int size);
int empty(int *top);
void init(int *top)
{
    *top = 0;
}
void push(char *s, int *top, char element)
{
    s[(*top)++] = element;
}
char pop(char *s, int *top)
{
    return s[--(*top)];
}
int full(int *top, const int size)
{
    return *top == size ? 1 : 0;
}
int empty(int *top)
{
    return *top == 0 ? 1 : 0;
}
bool check(char *par, char *s, int *top)
{
    for (int i = 0; par[i] != '\0'; i++)
    {
        if (par[i] == '(' || par[i] == '{' || par[i] == '[')
            push(s, top, par[i]);
        else
        {
            if (empty(top))
                return false;
            char ele = pop(s, top);
            bool flag = false;
            switch (par[i])
            {
            case ')':
                if (ele == '(')
                    flag = true;
                break;
            case '}':
                if (ele == '{')
                    flag = true;
                break;
            case ']':
                if (ele == '[')
                    flag = true;
                break;
            default:
                flag = false;
                break;
            }
            if (!flag)
                return false;
        }
    }
    if (empty(top))
        return true;
    return false;
}
int main()
{
    int top;
    char stack[SIZE];
    init(&top);
    char paranthesis[SIZE];
    printf("Enter the sequence:   ");
    scanf("%s", paranthesis);

    if (check(paranthesis, stack, &top))
    {
        printf("\nCorrect Sequence");
    }
    else
    {
        printf("\nIncorrect Sequence");
    }
    return 0;
}

Please comment in case of doubts or queries.
It would be really hepful if you could give an upvote :)

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
- implement the Stack ADT using the linked list approach. Use C++ program language #include "StackLinked.h"...
- implement the Stack ADT using the linked list approach. Use C++ program language #include "StackLinked.h" template StackLinked::StackLinked (int maxNumber) { } template StackLinked::StackLinked(const StackLinked& other) { } template StackLinked& StackLinked::operator=(const StackLinked& other) { } template StackLinked::~StackLinked() {    clear(); } template void StackLinked::push(const DataType& newDataItem) throw (logic_error) {    } template DataType StackLinked::pop() throw (logic_error) { } template void StackLinked::clear() {    StackNode* t;    while ( top != NULL)    {        t = top;       ...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped everytime instead of the one. If there is only one element in the stack, just pop the one element and report that the stack is now empty. If stack is empty, it should just report that stack is empty. All other functions for StackArray remain the same. using java StackArray.java: public class StackArray {       private final int size = 20; //Size of...
Given main() complete the Stack class by writing the methods push() and pop(). The stack uses...
Given main() complete the Stack class by writing the methods push() and pop(). The stack uses an array of size 5 to store elements. The command Push followed by a positive number pushes the number onto the stack. The command Pop pops the top element from the stack. Entering -1 exits the program. Ex. If the input is Push 1 Push 2 Push 3 Push 4 Push 5 Pop -1 the output is Stack contents (top to bottom): 1 Stack...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity  ...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity   Code   Description   Project   File   Line   Suppression State Warning   C6385   Reading invalid data from 'DynamicStack': the readable size is '(unsigned int)*28+4' bytes, but '56' bytes may be read.   Here is the C++ code were I'm having the warning. // Sstack.cpp #include "SStack.h" // Constructor SStack::SStack(int cap) : Capacity(cap), used(0) {    DynamicStack = new string[Capacity]; } // Copy Constructor SStack::SStack(const SStack& s) : Capacity(s.Capacity), used(s.used)...
Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the...
Instructions: SLLStack (12 pts) ● Using the two properties below, implement the stack interface using the SLLNode class from Lab 2: ○ top_node → SLLNode object or None ○ size → int, keep track of stack size ● Implement the push( ), pop( ), top( ) methods ● Use SLLNode methods: get_item( ), set_item( ), get_next( ), set_next( ) ● (5 pts) In push(item): ○ Create new SLLNode with item ○ Add new node before top node ○ Update top_node...
Using the C programming language implement Heapsort in the manner described in class. Here is some...
Using the C programming language implement Heapsort in the manner described in class. Here is some example code to use as a guideline. Remember, you need only implement the sort algorithm, both the comparison and main functions have been provided. /* * * after splitting this file into the five source files: * * srt.h, main.c, srtbubb.c, srtinsr.c, srtmerg.c * * compile using the command: * * gcc -std=c99 -DRAND -DPRNT -DTYPE=(float | double) -D(BUBB | HEAP | INSR |...
tacks. Trace the C++ program below showing all output in the order that it is displayed....
tacks. Trace the C++ program below showing all output in the order that it is displayed. If anything happens that makes it impossible to accomplish an operation or the results of so doing are unpredictable, describe what happens and abort the program at that point. Assume the Stack class is fully defined in an appropriate header and implementation file. The effect of the functions (methods) is as follows: constructor - creates an empty stack empty - returns true if the...
Consider a generic Stack class implemented using linked list with the following methods: public boolean isEmpty(),...
Consider a generic Stack class implemented using linked list with the following methods: public boolean isEmpty(), which returns true if and only if the stack is empty; public T pop() throws StackUnderflowException, which removes and returns the top element of the stack (if the stack is empty, it throws StackUnderflowException); public T peek() throws StackUnderflowException, which returns the top element of the stack (but does not remove it; it throws exception if stack is empty); public void push(T element), which...
(JAVA) Why is my toString method not printing out the last node? It will not print...
(JAVA) Why is my toString method not printing out the last node? It will not print out "A" which is for Alice. Everything else is working just fine except for this. package driver; import exception.StackException; import stack.*; public class StackDriver { public static void main(String[] args) throws Exception { StackInterface<Painting> painting = new LinkedStack <Painting>(); try { System.out.println("Peeking at top of player stack.\n" + painting.peek()); }catch (StackException e) { System.out.println(e); System.out.println("Let's double check if it's empty: " + painting.isEmpty()); }...
Stack2540Array import java .io .*; import java . util .*; public class Stack2540Array { int CAPACITY...
Stack2540Array import java .io .*; import java . util .*; public class Stack2540Array { int CAPACITY = 128; int top ; String [] stack ; public Stack2540Array () { stack = new String [ CAPACITY ]; top = -1; } 1 3.1 Implement the stack ADT using array 3 TASKS public int size () { return top + 1; } public boolean isEmpty () { return (top == -1); } public String top () { if ( top == -1)...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT