//
brackets_match.cpp : 定义控制台应用程序的入口点。
//
#include
"
stdafx.h
"
#include
"
c1.h
"
typedef
char
SElemType;
#define
STACK_INIT_SIZE 100
#define
STACKINCREMENT 10
#define
MAX 100
typedef
struct
{
SElemType
*
base
;
SElemType
*
top;
int
stacksize;
}SqStack;
Status InitStack(SqStack
*
S)
{
(
*
S).
base
=
(SElemType
*
)malloc(STACK_INIT_SIZE
*
sizeof
(SElemType));
if
(
!
(
*
S).
base
)
exit(OVERFLOW);
(
*
S).top
=
(
*
S).
base
;
(
*
S).stacksize
=
STACK_INIT_SIZE;
return
OK;
}
Status StackEmpty(SqStack S)
{
if
(S.top
==
S.
base
)
return
TRUE;
else
return
FALSE;
}
Status Push(SqStack
*
S,SElemType e)
{
if
((
*
S).top
-
(
*
S).
base
>=
(
*
S).stacksize)
{
(
*
S).
base
=
(SElemType
*
)realloc((
*
S).
base
,((
*
S).stacksize
+
STACKINCREMENT)
*
sizeof
(SElemType));
if
(
!
(
*
S).
base
)
exit(OVERFLOW);
(
*
S).top
=
(
*
S).
base
+
(
*
S).stacksize;
(
*
S).stacksize
+=
STACKINCREMENT;
}
*
((
*
S).top
++
)
=
e;
return
OK;
}
Status Pop(SqStack
*
S,SElemType
*
e)
{
if
((
*
S).top
==
(
*
S).
base
)
return
ERROR;
*
e
=*
(
--
(
*
S).top);
return
OK;
}
int
leftbrackets(
char
c)
{
if
(c
==
'
(
'
||
c
==
'
[
'
)
return
1
;
else
return
0
;
}
void
match(
char
*
newstr,
char
oldstr)
{
if
(oldstr
==
'
)
'
)
*
newstr
=
'
(
'
;
else
if
(oldstr
==
'
]
'
)
*
newstr
=
'
[
'
;
else
if
(oldstr
==
'
(
'
)
*
newstr
=
'
)
'
;
else
if
(oldstr
==
'
[
'
)
*
newstr
=
'
]
'
;
}
int
ismatch(
char
leftstr,
char
rightstr)
{
if
(leftstr
==
'
(
'
&&
rightstr
==
'
)
'
)
return
1
;
else
if
(leftstr
==
'
[
'
&&
rightstr
==
'
]
'
)
return
1
;
else
return
0
;
}
char
*
brackets_match(
char
*
newstr,
char
*
oldstr, SqStack S)
{
int
len,i
=
0
,j
=
0
;
char
e;
//
newstr=(char *)malloc(MAX*sizeof(char));
len
=
strlen(oldstr);
while
(i
<
len)
{
//
遇到的是右括号
if
(
!
leftbrackets(oldstr[i]))
{
//
如果栈为空,则在新字符串中将其与遇到的右括号配对
if
(StackEmpty(S))
{
match(
&
(newstr[j]),oldstr[i]);
j
++
;
newstr[j]
=
oldstr[i];
i
++
;
j
++
;
}
//
如果栈不为空,则出栈,并将出栈元素与遇到的右括号匹配
else
if
(
!
StackEmpty(S))
{
Pop(
&
S,
&
e);
//
如果匹配,则将遇到的括号存到新字符串中
if
(ismatch(e,oldstr[i]))
{
newstr[j]
=
oldstr[i];
j
++
;
i
++
;
}
//
否则,存入一个与出栈的括号相匹配的括号
else
{
/*
match(&(newstr[j]),oldstr[i]);
j++;
newstr[j]=oldstr[i];
i++;
j++;
*/
match(
&
(newstr[j]),e);
j
++
;
}
}
}
//
如果遇到的是左括号,则将左括号入栈,同时将其存入新字符串
else
if
(leftbrackets(oldstr[i]))
{
Push(
&
S,oldstr[i]);
newstr[j]
=
oldstr[i];
j
++
;
i
++
;
}
}
//
如果栈中还有元素没有弹出,则将剩下的左括号弹出并将匹配的括号存到新字符串中
while
(
!
StackEmpty(S))
{
Pop(
&
S,
&
e);
match(
&
(newstr[j]),e);
j
++
;
}
newstr[j]
=
'
\0
'
;
return
newstr;
}
int
_tmain(
int
argc, _TCHAR
*
argv[])
{
SqStack S;
/*
int e;
InitStack(&S);
int i;
for(i=0;i<5;i++)
Push(&S,i);
for(i=0;i<5;i++)
{
Pop(&S,&e);
printf("the element is %d\n",e);
}
*/
InitStack(
&
S);
char
*
oldstr
=
"
([(](
"
,
*
newstr;
printf(
"
the old str is %s\n
"
,oldstr);
newstr
=
(
char
*
)malloc(MAX
*
sizeof
(
char
));
newstr
=
brackets_match(newstr,oldstr, S);
printf(
"
the new string is %s\n
"
,newstr);
while
(
1
);
return
0
;
}