#include<stdio.h>
#include<stdlib.h>
#define N 100
struct cell{
int node;
struct cell *next;
};
void preorder(int k,struct cell **S);
void postorder(int k,struct cell **S);
void inorder(int k,struct cell **S);
int main(int argc,char* argv[]){
struct cell *S[N],*q,*p,*r,*s;
int root=0;
for(int i=0;i<N-1;i++) {
S[i]=(cell *)malloc(sizeof(cell));
S[i]->next=NULL;//S[N]のすべてのnextにNULLを入れる
S[i]->node=11;//S[N]のすべてに逃げる数字を入れる
}
//=====================================================================
//スタックと同じつなぎ方なので先に2を入れてから1を入れる
for(int i=2;i>0;i--){//nodeに1と2を入れるために2から1
q=(cell *)malloc(sizeof(cell));
q->node=i;//qのnodeに1と2を入れる
q->next=S[root]->next;//S[0]に1、1に2をつなげる
S[root]->next=q;
}
//==========================================================================
//上と同じつなぎ方でつなげる
for(int i=5;i>2;i--){
p=(cell *)malloc(sizeof(cell));
p->node=i;
p->next=S[1]->next;//S[1]に5、4、3をつなげる
S[1]->next=p;
}
//===========================================================================
for(int i=7;i>5;i--){
r=(cell *)malloc(sizeof(cell));
r->node=i;
r->next=S[2]->next;//S[2]に7、6をつなげる
S[2]->next=r;
}
//=============================================================================
for(int i=9;i>7;i--){
s=(cell *)malloc(sizeof(cell));
s->node=i;
s->next=S[6]->next;//S[6]に9,8をつなげる
S[6]->next=s;
}
printf("preorder:");
preorder(root,S);
printf("\npostorder:");
postorder(root,S);
printf("\ninorder:");
inorder(root,S);
printf("\n");
}
//===================前順=========================================================
/*ほぼ教科書と同じだが、S配列の中身は、参照したくないので
11を逃げにして、if(q->node==0) q=q->next;を書く。
これで、S配列の中のnodeは読まれない*/
void preorder(int k,struct cell **S)
{
struct cell *q;
printf("%d",k);//前順は先に数字を出力する
q=S[k];
if(q->node==11) q=q->next;//S配列のときは次へ
while(q!=NULL){
preorder(q->node,S);//再起呼び出し
q=q->next;
}
return;
}
//=======================後順========================================================
void postorder(int k,struct cell **S)
{
struct cell *q;
q=S[k];
if(q->node==11) q=q->next;
while(q!=NULL){
postorder(q->node,S);
q=q->next;
}
printf("%d",k);//後順は、後ろから
return;
}
//========================中順===========================================================
void inorder(int k,struct cell **S)
{
struct cell *q;
int count=0;
q=S[k];
if(q->node==11) q=q->next;
while(q!=NULL){
inorder(q->node,S);
if(count==0)printf("%d",k);
q=q->next;
count++;//ここを通るのが何回目なのかをカウントする
}
if(count==0)printf("%d",k);//1回目じゃなければ出力する
return;
}
等差数列の和の公式を使うとできるようだ
#include<stdio.h>
#include <stdlib.h>
void tousa(int ,int ,int );
int main(){
FILE *fp;
fp=fopen("../data1.txt","r");
int a;
int n;
int b;
fscanf(fp,"%d",&a);
fscanf(fp,"%d",&n);
fscanf(fp,"%d",&b);
tousa(a,n,b);
fclose(fp);
return 0;
}
void tousa(int a,int n,int r){
if(n!=0) {
printf("sum(%d)=%d\n ",n,(2*a+(n-1)*r)*n/2);
tousa(a,n-1,r);
}
}
完成です。