-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
92 lines (83 loc) · 1.67 KB
/
stack.c
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
// GROUP 39
// AKANKSHYA MISHRA 2016A7PS0026P
// NARAPAREDDY BHAVANA 2016A7PS0034P
// KARABEE BATTA 2016A7PS0052P
// AASTHA KATARIA 2016A7PS0062P
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include "lexer.h"
#include "stackDef.h"
void print_gram(gram_elem* e){
if(e->is_term){
printf("%s\n", TerminalString(e->elem.terminal));
}else{
printf("%s\n", nonTerminalStringTable[e->elem.nonterminal]->nonterminal);
}
}
gram_elem* top(Stack *s){
Ele *ptr=s->tail;
return ptr->el;
}
bool isEmpty(Stack *s){
if (s->size==0) return true;
return false;
}
Ele* pop(Stack *s){
if(isEmpty(s)) return NULL;
if(s->size==1) {Ele *ptr= s->head; s->head=NULL; s->tail=NULL; s->size--; return ptr;}
Ele *ptr = s->head;
while(ptr->next!=s->tail){ ptr=ptr->next; }
Ele *ret = s->tail;
s->tail=ptr;
s->size--;
return ret;
}
Ele* returnParseEle(bool is_term, int t){
Ele *e = (Ele*)malloc(sizeof(Ele));
e->el = (gram_elem*)malloc(sizeof(gram_elem));
e->el->is_term=is_term;
if(is_term){
e->el->elem.terminal=t;
}else{
e->el->elem.nonterminal=t;
}
e->next=NULL;
return e;
}
void push(Stack *s, Ele *e){
if(s->size==0){
s->head=e;
s->tail=e;
}else{
s->tail->next=e;
s->tail=e;
}
s->size++;
}
void pushAll(Stack *s, int rule_no){
// if(rule_no==-1) return;
g_node *g = grammar[rule_no]->next;
while(g->next!=NULL){
g=g->next;
}
while(g!=NULL){
if(g->is_term){
push(s, returnParseEle(1, g->elem.terminal));
}
else{
push(s, returnParseEle(0, g->elem.nonterminal));
}
g=g->prev;
}
}
int size(Stack *s){
return s->size;
}
Stack* newStack(){
Stack *s = (Stack*)malloc(sizeof(Stack));
s->size=0;
s->head=NULL;
s->tail=NULL;
return s;
}