题目要求基本如下:
请编写一个控制台程序,要求用户可以输入任意组条件,定义两个字母之间的大小关系。程序可以通过已输入的条件,推断出给定的两个字母之间的大小关系。例如:
用户输入:A>B
用户输入:B>C
用户输入:A?C
程序显示:A>C
用户输入:C<D
用户输入:A?D
程序显示:无法判断
用户输入:A<C
程序显示:与原有条件冲突
#include <cstdlib>
#include <iostream>
using namespace std;
/*
*数组依次存放A-Z,并保存大于和小于该字母的字母链表
*/
const int N = 26;
struct CharNode
{
CharNode( char n,CharNode* p):node(n),next(p){}
char node;
CharNode* next;
};
struct ArrayNode
{
int sign;
CharNode* up;
CharNode* down;
};
ArrayNode array[N];
void Init( )
{
for ( int i = 0; i < N; ++i )
{
array[i].sign = 0;
array[i].up = NULL;
array[i].down = NULL;
}
};
void Free( )
{
CharNode* pChar = NULL;
for ( int i = 0; i < N; ++i )
{
pChar = array[i].up;
while( NULL != pChar )
{
array[i].up = pChar->next;
delete pChar;
pChar = array[i].up;
}
pChar = array[i].down;
while( NULL != pChar )
{
array[i].down = pChar->next;
delete pChar;
pChar = array[i].down;
}
}
};
void Reset( )
{
for ( int i = 0; i < N; ++i )
array[i].sign = 0;
};
void InsertNodeUp( char arraynode, char c )
{
CharNode* pNode = new CharNode(c,NULL);
CharNode* pCharNode = array[arraynode-'A'].up;
if ( NULL != pCharNode )
pNode->next = pCharNode;
array[arraynode-'A'].up = pNode;
};
void InsertNodeDown( char arraynode, char c )
{
CharNode* pNode = new CharNode(c,NULL);
CharNode* pCharNode = array[arraynode-'A'].down;
if ( NULL != pCharNode )
pNode->next = pCharNode;
array[arraynode-'A'].down = pNode;
};
bool _FindUp( char source, char dest )
{
if ( source == dest )
return true;
if ( 1 == array[source-'A'].sign )
return false;
array[source-'A'].sign = 1;
CharNode* pChar = array[source-'A'].up;
while ( NULL != pChar )
{
if ( _FindUp(pChar->node,dest) )
return true;
pChar = pChar->next;
}
return false;
};
bool FindUp( char source, char dest )
{
Reset( );
return _FindUp(source,dest);
};
bool _FindDown( char source, char dest )
{
if ( source == dest )
return true;
if ( 1 == array[source-'A'].sign )
return false;
array[source-'A'].sign = 1;
CharNode* pChar = array[source-'A'].down;
while ( NULL != pChar )
{
if ( _FindDown(pChar->node,dest) )
return true;
pChar = pChar->next;
}
return false;
};
bool FindDown( char source, char dest )
{
Reset( );
return _FindDown(source,dest);
};
int main(int argc, char *argv[])
{
char first;
char compare;
char second;
char minchar;
Init( );
while( 1 )
{
cin >> first >> compare >> second;
minchar = first < second ? first:second;
switch( compare )
{
case '>':
if ( FindUp(first,second) )
{
cout << "Wrong" << endl;
break;
}
InsertNodeDown(first,second);
InsertNodeUp(second,first);
break;
case '<':
if ( FindDown(first,second) )
{
cout << "Wrong" << endl;
break;
}
InsertNodeUp( first,second );
InsertNodeDown( second,first );
break;
case '?':
if ( FindUp(first,second) )
{
cout <<first<<'<'<<second<<endl;
break;
}
if( FindDown(first,second) )
{
cout<<first<<'>'<<second<<endl;
break;
}
cout << "Unknown" << endl;
break;
case 'Q':
goto End;
}
}
End:
Free( );
system("PAUSE");
return EXIT_SUCCESS;
}