Created
May 18, 2010 07:57
-
-
Save naoyat/404748 to your computer and use it in GitHub Desktop.
C言語で、再帰呼び出しを使用せずに、文字列"(12 + 3) * ( 3 * (4 + 5 ))"を、優先順位が低い順に二分木に入れる関数を作成したいのですが・・・。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> // memset, fls | |
#define MAX_TREE_HEIGHT 10 | |
#define TREE_BUFSIZE (1<<MAX_TREE_HEIGHT) | |
#define MAX_PAREN_DEPTH 16 | |
int bits(int x){ | |
return 1+fls(x); | |
// return 8*sizeof(int) - __builtin_clz(x); | |
// for (int i=0,n=1;i<32;i++,n<<=1) if (x<n) return i; return 32;a | |
} | |
main() { | |
char str[] = "(12 + 3) * ( 3 * (4 + 5 ))"; | |
char n[TREE_BUFSIZE]; // tree | |
int st_[MAX_PAREN_DEPTH], st=-1; // stack | |
char *p, *q=n-1; | |
int w=1, i, pat, psize, dsize, ofs; | |
memset(n,0,TREE_BUFSIZE); | |
//q[w] = 0; | |
for(p=str; *p; p++) { | |
switch(*p){ | |
case ' ': continue; | |
case '(': q[w] = 0; st_[++st]=w; break; | |
case ')': w=st_[st--]; break; | |
case '+': case '*': case '-': case '/': | |
pat=w, psize=bits(w); | |
for (i=TREE_BUFSIZE-1; i>w; i--) { | |
dsize = bits(i); | |
if (i >> (dsize-psize) == pat) { | |
ofs = w << (dsize-psize-1); | |
q[i] = q[i-ofs]; | |
} | |
} | |
q[w]=*p; q[w=w*2+1] = 0; | |
break; | |
default: // digits | |
q[w]=q[w]*10+(*p-'0'); break; | |
} | |
} | |
char ans[15] = { '*', '+', '*', 12, 3, 3, '+', 0, 0, 0, 0, 0, 0, 4, 5 }; | |
int correct = 1; for (i=0;i<15;i++) if (ans[i]!=n[i]) { correct=0; break; } | |
printf("%s\n", correct ? "Correct." : "Wrong."); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment