-
need help with stack
Write code that will determine the number of common unique elements in
the two stacks. For example, S has elements (top to bottom): 1, 2, 3, 3, 4, 5,
6; T has elements (top to bottom): 1, 3, 5, 5, 7. The common elements are
1, 3 and 5. The function should therefore return 3.
this is what i have and its not working... help pleasee
Code:
#include <iostream>
#include <cstdlib>
#include <stack>
using namespace std;
int cce(stack<int>& S, stack<int>& T);
int main()
{
stack<int> S;
stack<int> T;
S.push(1);
S.push(2);
S.push(3);
S.push(3);
S.push(4);
S.push(5);
T.push(1);
T.push(3);
T.push(5);
T.push(5);
T.push(7);
cout<<cce(S,T);
system ("PAUSE");
return 0;
}
int cce(stack<int>& S, stack<int>& T)
{
stack <int> temp;
int count = 0;
for(int x = S.size(); x>=1; x--)
{
for(int i = T.size(); i>=1; i--)
{
if(S.top()==T.top())
{
count++;
temp.push(T.top());
T.pop();
}
else
{
temp.push(T.top());
T.pop();
}
}
for(int y = temp.size(); y>=1; y--)
{
T.push(temp.top());
temp.pop();
}
}
}
-
Where do you go to the next element in the S stack?
I don't see S.pop()
I think the outter loop should be like
Code:
while(S.size() > 0)
{
// do your work with S.top()
S.pop();
}
-
i changed it it to a while loop added the pop but still not working. any more ideas please
-
i dont it this way as well but cant seem executing...please help
Code:
#include <iostream>
#include <cstdlib>
#include <stack>
using namespace std;
int cce(stack<int>& S, stack<int>& T);
int main()
{
stack<int> S;
stack<int> T;
S.push(1);
S.push(2);
S.push(3);
S.push(3);
S.push(4);
S.push(5);
T.push(1);
T.push(3);
T.push(5);
T.push(5);
T.push(7);
cout<<cce(S, T)<<endl;
system ("PAUSE");
return 0;
}
int cce(stack<int>& S, stack<int>& T)
{
int count=0;
while(S.size() > 0)
{
if(S.top() < T.top())
{
T.pop();
}
else if(T.top()< S.top())
{
S.pop();
}
else
{
count = count + 1;
T.pop();
while( T.size() > 0)
{
if(S.top() == T.top())
T.pop();
}
S.pop();
}
}
return count;
}
-
what about
Code:
int cce(stack<int>& S, stack<int>& T)
{
int count=0;
while(S.size() > 0 && T.size() > 0)
{
if(S.top() < T.top())
{
T.pop();
}
else if(T.top()< S.top())
{
S.pop();
}
else
{
count++;
T.pop();
S.pop();
}
}
return count;
}