//第一题匹配括号字符的解答,双向链表加堆栈
//另外有研究五子棋的没,本人希望跟各位讨论讨论,最好合作。
//那个程序我已传到一个帖子上面。有兴趣的可以去看看! :D
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
typedef char DataType;
typedef struct node
{
DataType data;
struct node * L_link;
struct node * R_link;
}Node;
Node * top;
Node * tail;
int flag_for_tail = 0;
int flag_for_first_top = 0;
void Push( DataType x )
{
Node * p;
p = ( Node * )malloc(sizeof(Node)); //建立的一个双向链表
p->data = x;
p->R_link = NULL;
if( flag_for_first_top == 0 )
{
top = p;
flag_for_first_top = 1;
}
else
{
p->L_link = top;
top->R_link = p;
top = p;
}
if( flag_for_tail == 0 ) //用来设置tail 指针
{
tail = p;
flag_for_tail = 1;
}
}
DataType Pop( )
{
Node * p;
DataType x;
x = top->data;
p = top;
top = top->L_link;
top->R_link = NULL;
free( p );
return x;
}
DataType Get_tail_value_and_Change_tail( )
{
Node * p;
DataType x;
x = tail->data;
p = tail;
tail = tail->R_link ;
tail->L_link = NULL;
free( p );
return x;
}
int _tmain(int argc, _TCHAR* argv[])
{
char str[100];
int i = 0;
char kk[2] ;
int ori_dengji = 5;
int temp_dengji = 5;
int number = 0;
printf("\n\n\t\t\t字符扫描匹配系统 \n\n\n");
printf("\n\n\t题目:给出一个包含各种括号的表达式,判断括号是否配对。括号配对的条件:\n");
printf("\n\n括号必须先左后右,并且左右括号数量相等;对于多重括号,从外到内嵌套顺序为:\n");
printf("\n\n{} -> [] -> () -> <>。例如{[(<>)]}。合法返回true, 否则返回false\n");
printf("\n\n\n\n\t输入范例:\n\n\n");
printf("\t\t{[(<>)]}\n");
printf("\t\t{}\n");
printf("\t\t<(>)\n");
printf("\t\t<()>\n\n");
printf("\t\t返回:\n");
printf("\t\ttrue\n");
printf("\t\ttrue\n");
printf("\t\tfalse\n");
printf("\t\tfalse\n");
printf("\n\n\n\tInput the string(请输入你想检测的括号串,并且以'!'结尾):");
gets(str);
while(str[i]!='!')
{
Push( str[i] ); //先将所有的字符入堆栈
i++;
}
if( i % 2 == 1 )
{
printf("\n\t经扫描,此字符串不匹配\n");
getchar();
getch();
return 0;
}
while( number < i % 2 + 1 )
{
kk[0] = Pop( );
kk[1] = Get_tail_value_and_Change_tail( );
if( kk[1] == '{' )
{
temp_dengji = 4;
if( temp_dengji > ori_dengji )
break;
if( kk[0] != '}' )
break;
ori_dengji = temp_dengji;
}
else if( kk[1] == '[' )
{
temp_dengji = 3;
if( temp_dengji > ori_dengji )
break;
if( kk[0] != ']')
break;
ori_dengji = temp_dengji;
}
else if( kk[1] == '(' )
{
temp_dengji = 2;
if( temp_dengji > ori_dengji )
break;
if( kk[0] != ')' )
break;
ori_dengji = temp_dengji;
}
else
{
temp_dengji = 1;
if( temp_dengji > ori_dengji )
break;
if( kk[0] != ']' )
break;
ori_dengji = temp_dengji;
}
number++;
}
if( number == i % 2 + 1)
printf("\n\t经扫描,此字符串匹配\n");
else
printf("\n\t经扫描,此字符串不匹配False\n");
getchar();
getch();
return 0;
}
[此贴子已经被作者于2007-3-23 10:52:27编辑过]