Sei sulla pagina 1di 2

// Expression.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
typedef struct term_s {
int start; // start position
int end; // end position
int level; // priority
term_s *next; // pointer to next term
} Term;
typedef struct term_list_s
{
Term *first;
Term *last;
int count;
} TermList;
TermList *CreateTermList(){
TermList *p = (TermList *)malloc(sizeof(TermList));
p->first = p->last = 0;
p->count = 0;
return p;
}
Term* CreateTerm(int level = 0, int start = 0, int end = -1 )
{
Term *p = (Term *)malloc(sizeof(Term));
p->next = 0;
p->start = start; // p la con tro nen muon truy cap vao thanh phan trong no th
dng du ->
p->end = end;
p->level = level;
return p;
}

ostream& operator<<(ostream& o,TermList* list){


Term*p = list->first;
while(p != 0)
{
o << p->start << ", "
<< p->end<< ", "
<< p->level << endl;
p = p->next;
}
return o;
}
int IsDigit(char c)
{
if('0' <= c && c <= '9')
return 1;
return c == '.';
}
int GetLevel(char c)
{
if(IsDigit(c))
return 0;
switch(c)
{
case ')': return -1;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
}
return -2;
}

void Append(TermList* list, Term*p){ // Noi vao cuoi 1 TermList


if(list->count++ == 0)
list -> first = p;
else
list -> last->next = p;
list->last = p;
}
void Push(TermList* list, Term*p){
if(list->count++ == 0)
list->first = list->last = p;
else{
p->next = list->first;
list->first = p;
}
}
Term *Pop(TermList* list){
Term *p = list -> first;
list -> first = p->next;
if(--list->count == 0)
list->last = 0;
return p;
}
int _tmain(int argc, _TCHAR* argv[])
{
char s[] = "1+2*3.5-40";
TermList *trungto = CreateTermList();
int i = 0;
while( char c = s[i]){
Term*p = CreateTerm(GetLevel(c),i,i);
if(p->level == 0)
{
while(IsDigit(s[++i]));
p->end = i-1;
}
Append(trungto, p);
i = p->end + 1;
}
cout<<" Trung to: "<<trungto;
return 0;
}

Potrebbero piacerti anche