Implementation of anagrams using stack in c++.(displays anagram if two texts are anagram but fails to display if texts are not anagram)

  anagram, c++, data-structures, segmentation-fault, stack

/this code compares 1st letter of first word with each letter of 2nd word and moves to 2nd letter of 1st word and next letter of 2nd word when both letter matches else pushes the letters of 2nd word to stack. Then each letter of 1st word is compared with elements of stack and popped out when both letter matches else puts the top elements of stack into an array till element of top matches the letter of 1st word. When stack becomes empty, comparison is done with array elements till all the letters of 1st word is completed./
/eg:POLO LOOP 1:(STACK:L O O )(P&P are equal) 2:(STACK:L O O)O&O are equal popped out 3:(STACK:L O) L not equal to O so O is popped out and put into an array 4:(STACK:L)L is equal to L popped out 5:no elements in stack so O is compared with element in array it matches/
/eg:LOOP POLO 1.STACK:P O(1st word moves to O 2nd word moves to O) 2:O(2nd letter of 1st word)and O (4th letter of 2nd word)equal 3:[STACK:P O]1st word moves to O and checks with stack(O popped out) 4:[STACK:P]similarly P popped out/

    #include<iostream>
    #include<stack>
    #include<cstring>
    using namespace std;
    int main()
    {
        stack<char>s;
        int i=0,j=0,k,n=0,c;
        char s1[10];
        char s2[10];
        char temp,a[10],d=0;
        cout<<"nEnter s1 and s2n";
        cin>>s1;
        cin>>s2;
        if(strlen(s1)==strlen(s2))
        {
            for(k=0; k<strlen(s1); k++)
            {
                if(s1[i]==s2[j])
                {
                    i=i+1;
                    j=j+1;
                }
                else
                {
                    s.push(s2[j]);
                    j=j+1;
                }
            }
    
            while(!(s.empty()))
            {
                if(s1[i]==s.top())
                {
                    s.pop();
                    i=i+1;
                }
                else
                {
                    a[d]=s.top();
                    n=n+1;
                    d=d+1;
                    s.pop();
                }
    
    
            }
    
    
            if(s.empty())
            {
                while(i<strlen(s1))
                {
                    for(c=0; c<n; c++)
                    {
                        if(s1[i]==a[c])
                        {
                            temp=a[c];
                            i=i+1;
                        }
                    }
                }
            }
    
        }
        if(i==strlen(s1))
            cout<<"ANAGRAM";
        else
            cout<<"NOT ANAGRAM";
        return 0;
    }

Source: Windows Questions C++

LEAVE A COMMENT