-
Notifications
You must be signed in to change notification settings - Fork 0
/
balancing symbol
107 lines (102 loc) · 1.76 KB
/
balancing symbol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//
// main.c
// balancing symbol
//
// Created by 毛遵杰 on 2019/11/12.
// Copyright © 2019 毛遵杰. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char symbol;
struct node* next;
}Node;
typedef struct node* stack;
typedef struct node* position;
stack makeStack(void);
int isEmpty(stack p);
void push(stack p,char X);
void pop(stack p);
char top(stack p);
int match(char p,char q);
void checkSymbols(stack p);
stack makeStack(void)
{
stack p=(struct node*)malloc(sizeof(struct node));
if(p==NULL)
printf("memory error");
else
{
p->next=NULL;
return p;
}
}
int isEmpty(stack p)
{
return p->next==NULL;
}
void push(stack p,char X)
{
if(p==NULL)
printf("Please make a stack first");
position q = (struct node*)malloc(sizeof(struct node));
if(q==NULL)
printf("memory error");
else
{
q->symbol=X;
q->next=p->next;
p->next=q;
}
}
void pop(stack p)
{
position q;
if(isEmpty(p))
printf("Empty space");
else
{
q=p->next;
p->next=p->next->next;
free(q);
}
}
char top(stack S)
{
return S->next->symbol;
}
int match(char m,char n)
{
if(abs(m-n)==1)
return 1;
else if(abs(m-n)==2)
return 1;
else
return 0;
}
void checkSymbols(stack p)
{
char sy;
while((sy=getchar())!='#')
{
if(sy=='{'||sy=='['||sy=='(')
push(p,sy);
else
if(sy=='}'||sy==']'||sy==')')
{
if(match(sy,top(p)))
pop(p);
else
printf("error");
}
}
if(isEmpty(p))
printf("right\n");
}
int main(int argc, char *argv[])
{
stack p = makeStack();
checkSymbols(p);
return 0;
}