Am new to template concept , and was trying to make a Generic Stack , and try balanced parenthesis problem on it. When tried to build the code, I am getting the error C2990
in Visual Studio 2010. The code is as under. Kindly suggest me a solution , as am stuck with this problem , and can't find a solution to it.
Extact Error :- error C2990: 'node' : non-class template has already been declared as a class template
template<class T>
struct node {
T data;
struct node * next;
};
template<class T>
class Stack {
struct node *top;
public :
Stack() {
top = NULL;
}
void push(T value);
T pop();
T peek();
int isEmpty();
};
template<class T>
void Stack<T>::push(T value) {
struct node *new_node = new node;
if(new_node == NULL) {
cout << "Stack Overflow" << endl;
return;
}
new_node->data = value;
if(top != NULL) {
new_node->next = top;
top = new_node;
} else {
top = new_node;
new_node->next = NULL;
}
}
template<class T>
T Stack<T>::pop() {
if(top == NULL) {
cout << "Stack Underflow" << endl;
return ;
}
T value = top->data;
struct node *tmp = top;
top = top->next;
free(tmp);
return value;
}
template<class T>
T Stack<T>::peek() {
if(top == NULL) {
cout << "Stack Underflow" << endl;
return ;
}
return top->data;
}
template<class T>
int Stack<T>::isEmpty() {
if(top == NULL)
return TRUE;
return FALSE;
}
int balanced(char a, char b) {
switch(a) {
case '[' :
if(b == ']')
return TRUE;
return FALSE;
case '{' :
if(b == '}')
return TRUE;
return FALSE;
case '(' :
if(b == ')')
return TRUE;
return FALSE;
}
}
int isOpeningParenthesis(char a) {
if(a == '[' || a == '{' || a == '(')
return TRUE;
return FALSE;
}
int isClosingParenthesis(char a) {
if(a == ']' || a == '}' || a == ')')
return TRUE;
return FALSE;
}
int balancedParenthesis(char *arr, int length) {
int i;
Stack<char> *s = new Stack<char>;
for(i=0; i<length; i++) {
if(TRUE == isOpeningParenthesis(arr[i]))
s->push(arr[i]);
else if(TRUE == isClosingParenthesis(arr[i])){
if((TRUE == s->isEmpty()) || (FALSE == balanced(s->pop(), arr[i])))
return FALSE;
}
}
if(FALSE == s->isEmpty())
return FALSE;
return TRUE;
}
int main() {
char a1[10] = {'{','[',']','(','(',')',')','[',']','}'};
char a2[5] = {'[','[',']',']','}'};
for(int i = 0; i < 10; i++)
cout << a1[i] << " ";
cout << endl;
if(TRUE == balancedParenthesis(a1, sizeof(a1)/sizeof(a1[0])))
cout << "Balanced Parenthesis " << endl;
else
cout << "Not balanced parenthesis" << endl;
for(int i = 0; i < 5; i++)
cout << a2[i] << " ";
cout << endl;
if(TRUE == balancedParenthesis(a2, sizeof(a2)/sizeof(a2[0])))
cout << "Balanced Parenthesis " << endl;
else
cout << "Not balanced parenthesis" << endl;
getch();
return 0;
}