-->
当前位置:首页 > 题库 > 正文内容

程序填空题:括号匹配算法

Luz4年前 (2021-05-10)题库2461
实现两种括号的匹配判断

```c

#include
#include

typedef int DataType;
struct Node {
DataType data;
struct Node* next;
};
typedef struct Node *PNode;
typedef struct Node *LinkStack;

LinkStack SetNullStack_Link()
{
LinkStack top = (LinkStack)malloc(sizeof(struct Node));
if (top != NULL) top->next = NULL;
else printf("Alloc failure");
return top;
}

int IsNullStack_link(LinkStack top)
{
if (top->next == NULL)
return 1;
else
return 0;
}

void Push_link(LinkStack top, DataType x)
{
PNode p;
p = (PNode)malloc(sizeof(struct Node));
if (p == NULL)
printf("Alloc failure");
else
{
p->data = x;
p->next = top->next;
top->next = p;
}
}
void Pop_link(LinkStack top)
{
PNode p;
if (top->next == NULL)
printf("it is empty stack!");
else
{
p = top->next;
top->next = p->next;
free(p);
}
}
DataType Top_link(LinkStack top)
{
if (top->next == NULL)
{
printf("It is empty stack!");
return 0;
}
else
return top->next->data;
}

void BracketMatch(LinkStack top)
{
int flag = 1;
char ch, temp;
scanf("%c", &ch);
while (ch != '#')
{
switch (ch) {
case '[':
case '(':
@@[Push_link(top, ch)](2);
@@[break](2);
case ')':
if (@@[Top_link(top) == '('](2))
Pop_link(top);
else
flag = 0;
break;
case ']':
if (@@[Top_link(top) == '['](2))
Pop_link(top);
else
flag = 0;
break;
}//swith
scanf("%c", &ch);
}//while

if (@@[!flag || !IsNullStack_link(top)](2))
printf("no!");
else
printf("yes!");
}

int main()
{
LinkStack mystack = NULL;
mystack = SetNullStack_Link();
BracketMatch(mystack);
return 0;
}
```






答案:
第1空:Push_link(top, ch)

第2空:break

第3空:Top_link(top) == '('

第4空:Top_link(top) == '['

第5空:!flag || !IsNullStack_link(top)

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。