• 締切済み

c言語の問題です。ファイルからデータを読み込み連結リストに記憶しソートするプログラムです。お願いします

ソート部分がどうしてもできません。 またソートは以下のアルゴリズムで行うものです 与えられたリストをリストA、ソート済みのリストをリストBとする。処理の開始段階では、リストBは空である。 1.リストAの要素の中で、最大値をもつ要素Cを探す。 2.要素CをリストAから削除する。 3.要素CをリストBの先頭に挿入する。 4.リストAが空であれば終了。空でなければ 1. にもどる。 #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct physical Physical; struct physical { char name[41]; int age; float height; float weight; Physical *next; }; void read_data(char *file,Physical *p,Physical *tail); int comp1(const Physical *, const Physical *); int comp2(const Physical *, const Physical *); int comp3(const Physical *, const Physical *); int comp4(const Physical *, const Physical *); void sort(char *arg,Physical *p,Physical *q); Physical *listsort(Physical *p, int (*compar)(const void *, const void *)); int main(void) { char s[20],t,u[20]; Physical *p,*tail,*q; p=malloc(sizeof(Physical)); q=malloc(sizeof(Physical)); tail=malloc(sizeof(Physical)); while(1) { printf("CMD>"); fflush(stdout); fgets(s,20,stdin); sscanf(s,"%c %s",&t,u); switch(t){ case 'q':exit(0); case 'r':read_data(u,p,tail); break; case 's':sort(u,p,q); break; case 'd': while(q!=NULL) { printf("%s %d %.1f %.1f ",q->name,q->age,q->height,q->weight ); q=q->next;} break; } } free(p); return 0; } void read_data(char *file,Physical *p,Physical *tail){ FILE *fp; char string[100]; Physical header; tail=&header; header.next = NULL; p->next = NULL; tail->next = p; tail = p; if ((fp = fopen(file, "r")) == NULL) { exit(1); } while(fgets(string,sizeof(string),fp)!= NULL) { sscanf(string,"%s %d %f %f",p->name,&p->age,&p->height,&p->weight); Physical *tail2; tail2=malloc(sizeof(Physical)); tail2->next=NULL; p->next=tail2; p=tail2; } fclose(fp); } void sort(char *arg,Physical *p,Physical *q){ if(strcmp(arg,"name") == 0) q=listsort(p,(int(*)(const void*, const void*))comp1); if(strcmp(arg,"age") == 0) q=listsort(p,(int(*)(const void*, const void*))comp2); if(strcmp(arg,"height") == 0) q=listsort(p,(int(*)(const void*, const void*))comp3); if(strcmp(arg,"weight") == 0) q=listsort(p,(int(*)(const void*, const void*))comp4); } Physical *listsort(Physical *p,int (*compar)(const void *, const void *)){ Physical *q, *max,*s,*head; s=malloc(sizeof(Physical)); head=malloc(sizeof(Physical)); head=NULL; while(p->next){max = p, q = p->next; while( q->next ) { if( compar(q->next,max->next) ) max = q; q = q->next;} s=max->next; max->next=max->next->next; if(head==NULL) {head=s;} s->next=s; } return head; } int comp1(const Physical *a, const Physical *b){ return (strncmp(a->name,b->name,sizeof(Physical))); } int comp2(const Physical *a, const Physical *b){ if(a->age > b->age) return 1; else return 0; } int comp3(const Physical *a, const Physical *b){ if(a->height > b->height) return 1; else return 0; } int comp4(const Physical *a, const Physical *b){ if(a->weight > b->weight) return 1; else return 0; }

みんなの回答

  • yama5140
  • ベストアンサー率54% (136/250)
回答No.3

>またソートは以下のアルゴリズムで行うものです >与えられたリストをリストA、ソート済みのリストをリストBとする。処理の開始段階では、リストBは空である。 >1.リストAの要素の中で、最大値をもつ要素Cを探す。 >2.要素CをリストAから削除する。 >3.要素CをリストBの先頭に挿入する。 >4.リストAが空であれば終了。空でなければ 1. にもどる。  リストA、リストBとありますが、リストAだけの方が簡単だと思います。  「やはりリストBも用いて、手順どおりに」でしたら、以降無視して下さい。 ++++++++++++++++++++++++++++++++ ☆リストAだけのもので、ソート機能を確認することを主目的に、簡便化したものを投稿します。  ・この手の処理では、構造体(頭)はグローバルが易しいかと。  ・リスト「入れ換え」の注意点として、アドレスは入れ換えない(◆)ことです(入れ物はそのままで、中身のみ入り換え)。   なお、comp1() は、思うように機能しませんでした・・残念。 用いたデータ( test.txt ) abc 18 170.2 68.3 xxx 19 173.4 65.1 nnn 55 170.1 80.4 yyy 30 172.3 66.2 ++++++++++++++++++++++++++++++++ #1 さんへ ひょっとして #include <stdio.h> void foo(int *x) { *x = 4; } int main() { int x = 3; foo(&x); printf("%d\n", x); return 0; } というプログラムで、「4」が出力されると質問者様は、確信しているのでは? #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct _cell{  char name[ 32 ]; // 奇数キライ  int age;  float height;  float weight;  struct _cell *next; }PHYSICAL; PHYSICAL sgHead; int comp1( const PHYSICAL *a, const PHYSICAL *b ){ return ( strncmp( a->name, b->name, sizeof(PHYSICAL) ) ); } int comp2( const PHYSICAL *a, const PHYSICAL *b ){ if( a->age > b->age ) return 1; return 0; } int comp3( const PHYSICAL *a, const PHYSICAL *b ){ if( a->height > b->height ) return 1; return 0; } int comp4( const PHYSICAL *a, const PHYSICAL *b ){ if( a->weight > b->weight ) return 1; return 0; } void read_data( char *file ) {  FILE *fp;  char string[ 64 ];  PHYSICAL *p, *q, *new_p;  if( ( fp = fopen( file, "r" ) ) == NULL ) exit( 1 );  while( fgets( string, sizeof( string ), fp ) != NULL ){   p = sgHead.next;   q = &sgHead;   while( NULL != p ){    q = p;    p = p->next;   }   new_p = (PHYSICAL *)malloc( sizeof(PHYSICAL) ); // 1人分のメモリ確保   sscanf( string, "%s %d %f %f", new_p->name, &new_p->age, &new_p->height, &new_p->weight );   new_p->next = NULL;   q->next = new_p;  }  fclose( fp ); } void listsort( int (*compar)( const PHYSICAL *, const PHYSICAL * ) ) {  PHYSICAL *q, *s, tmp;  long lTmp;  for( q = sgHead.next; NULL != q; q = q->next ){   for( s = q->next; NULL != s; s = s->next ){    if( compar( q, s ) ){     tmp = *q;     *q = *s;     *s = tmp;     lTmp = (long)q->next; // ◆アドレスを戻す     q->next = s->next;     s->next = (PHYSICAL *)lTmp;    }   }  } } void sort( char *arg ) {  if( strcmp( arg, "name" ) == 0 ) listsort( ( int(*)( const PHYSICAL *, const PHYSICAL * ) )comp1 );  if( strcmp( arg, "age" ) == 0 )  listsort( ( int(*)( const PHYSICAL *, const PHYSICAL * ) )comp2 );  if( strcmp( arg, "height" ) == 0 ) listsort( ( int(*)( const PHYSICAL *, const PHYSICAL * ) )comp3 );  if( strcmp( arg, "weight" ) == 0 ) listsort( ( int(*)( const PHYSICAL *, const PHYSICAL * ) )comp4 ); } void Output( void ) {  PHYSICAL *q;  q = sgHead.next;  while( q != NULL ){   printf( "%-16s %d %.1f %.1f\n", q->name, q->age, q->height, q->weight );   q = q->next;  }  printf( "\n" ); } void AllDeleteList( void ) {  PHYSICAL *p;  while( NULL != sgHead.next ){   p = sgHead.next;   sgHead.next = p->next;   free( p );  } } void main( void ) {  sgHead.next = NULL;  read_data( "test.txt" );  Output(); // 出力  sort( "height" ); // 身長でソート  Output(); // 出力  AllDeleteList(); // メモリ解放 } 注:インデントに全角空白を用いています。コピペ後、タブに一括変換して下さい。

  • asuncion
  • ベストアンサー率33% (2126/6288)
回答No.2

ソースコードをすべて見たわけではありませんが、 気になる点があります。 listsort関数の下記コードで >head=malloc(sizeof(Physical)); >head=NULL; mallocでせっかく確保した領域が、直後の文でムダになるとともに、 メモリリークを起こしています。 これはまずいです。 この2つの文を連続して書いた理由は、どういったものですか? また、mallocの呼び出し全般についていえることは、 mallocによる領域確保は必ず成功する「とは限りません」。 戻り値をチェックすることは必須です。

  • Tacosan
  • ベストアンサー率23% (3656/15482)
回答No.1

「ソート部分がどうしてもできません。」というのはどのような状態を指しているのでしょうか? あと, ひょっとして #include <stdio.h> void foo(int x) { x = 4; } int main() { int x = 3; foo(x); printf("%d\n", x); return 0; } というプログラムで「4」が出力されると思ってはいないですよね?

関連するQ&A

  • C++ 連結リストの結合について

    現在、C++で連結リストの結合を実現しようとしているのですが、自分のやり方ではどうしてもエラーになってしまい、他にうまい実現方法が思いつかないので質問させていただきます。 以下が私が作ったプログラムなのですが、どこをどう変えたらうまく行くのか、具体的に教えて頂けたら嬉しいです。結合関数はaddAll(List &l)です。よろしくお願いします。 #include <iostream> using namespace std; class Cell{ private: int data; Cell *next; public: Cell(int d, Cell *n = NULL){ data = d; next = n; } friend class List; }; class List{ private: Cell *head; public: List(){ head = NULL; } ~List(){ while (head != NULL)removeFirst(); } void addLast(int data); void removeFirst(); void print(); void addAll(List &l); }; void List::addLast(int data){ if (head == NULL){ head = new Cell(data); } else{ Cell *p = head; while (p->next != NULL){ p = p->next; } p->next = new Cell(data); } } void List::removeFirst(){ if (head == NULL){ return; } else if (head->next == NULL){ delete head; return; } Cell *removed = head; head = head->next; delete removed; } void List::print(){ if (head == NULL){ return; } for (Cell *p = head; p != NULL; p = p->next){ cout << p->data << ' '; } cout << endl; } void List::addAll(List &l){ if (l.head == NULL){ return; } else if (head == NULL){ if (l.head == NULL){ return; } else{ head = l.head; return; } } else{ Cell *p = head; while (p->next != NULL){ p = p->next; } p->next = l.head; } return; } int main(){ List l1; l1.addLast(1); l1.addLast(2); l1.addLast(3); l1.print(); List l2; l2.addLast(4); l2.addLast(5); l2.addLast(6); l1.addAll(l2); l1.print(); return 0; } 実行結果は 1 2 3 1 2 3 4 5 6 と表示されればOKです

  • 連結リストをソート

    学校の課題なんですが正直手も足も出ません。 どういった流れで作成すればいいんでしょうか。 1.連結リストにデータ(文字列)をソートされた順序に追加するようなプログラムを作成する. 2.連結リストのデータを順にプリントするプログラムを作成する。 3.セルをキーとそれに対応する値を含めるように拡張し、与えられたキーを持つセルを探索して  それに対する値を返すプログラムを作成する。 課題を解く際には以下のプログラムを参考にする #include <stdio.h> struct element{ char data; struct element *next; }; struct elements *new() { return((struct element *)malloc(sizeof(struct element))); } struct element *create() { struct element *p; p=new(); p->next=NULL; return(p); } void insert(struct element *l,int k,char item) { struct element *p; if(k>1) insert(l->next,k-1,item); else{ p=new(); p->data=item; p->next=p; l->next=p; } } void delete(struct element *l,int k) { if(k>1) delete(l->next,k-1); else l->next=l->next->next; } char access(struct element *l,int k) { if(k>1) return(access(l->next,k-1)); else return(l->next->data); }

  • C言語のプログラム

    以下のプログラムはハッシュテーブルを用いて文字列を探すプログラムなのですが、コンパイル時にセグメントエラーとなってしまいます。プログラム中に誤った箇所があれば教えて頂きたいです。 #include <stdio.h> #include <stdlib.h> #include <string.h> #define HASHSIZE 10 #define MAX_LEN 64 #define N_WORDS 4 struct list { char word [MAX_LEN]; struct list *next; }; struct list *hash_table[HASHSIZE]; char colors[N_WORDS][MAX_LEN] = {"red", "blue", "green", "yellow"}; void my_strcpy(char* a, const char* b) { int i = 0; while(*b != '\0'){ *(a+i) = *(b+i); i++; } *(a+i) = '\0'; } int hash(char *key) { int hashval = 0; while (*key != '\0') { hashval += *key; key++; } return (hashval % HASHSIZE); } int find_word (char *key) { struct list *p; for (p = hash_table[hash(key)]; p != NULL; p++) if (strcmp(key, p->word) == 0) return 1; return 0; } void init_hash_table() { int i, hashvalue; struct list *p, *q; for (i = 0; i < HASHSIZE; i++) { hash_table[i] = NULL; } for (i = 0; i < N_WORDS; i++) { if ((find_word(colors[i])) == 0){ p = (struct list *)malloc(sizeof(struct list)); my_strcpy(p->word, colors[i]); hashvalue = hash(colors[i]); if (hash_table[hashvalue] = NULL) { hash_table[hashvalue] = p; p->next=NULL; } else { q = hash_table[hashvalue]; while (q->next != NULL) q = q->next; q->next = p; p->next=NULL; } } } } void main(void) { init_hash_table(); printf("result = %d\n", find_word("red")); }

  • C言語のソートについて

    C言語で下記のファイルの中身を昇順と降順で出力しようとしているのですが、ソートが上手くいっていない状況です。 どなたか修正点を教えて頂けないでしょうか? 「ファイルの中身」 2022/11/14 16:19:56 4+4,8.000000 2022/11/14 16:20:14 7+7,14.000000 2022/11/14 16:20:18 8+8,16.000000 2022/11/15 16:19:56 4+4,8.000000 2022/11/14 16:20:14 7+7,14.000000 2022/11/18 16:20:18 8+8,16.000000 2022/11/17 16:19:56 4+4,8.000000 2022/11/14 16:20:14 7+7,14.000000 2022/11/14 16:20:18 8+8,16.000000 「ソースコード」 #include <stdio.h> #include <string.h> #include <stdlib.h> int cmp_u(const void* a, const void* d) { return *(char*)a - *(char*)d; } int cmp_d(const void* a, const void* d) { return *(char*)d - *(char*)a; } int main() { int r,i,n; FILE* fp; char sin[9][1000]; fp = fopen("log.txt", "r"); if (fp == NULL) { printf("ファイルオープン失敗\n"); return -1; } for (i = 0; i < 9; i++) { fscanf(fp, "%s", &(sin[i])); } fclose(fp); printf("ASC or DESC: "); scanf(" %s", &ad); if (strcmp(ad, "ASC") == 0) { qsort(sin, 9, sizeof(char), cmp_u); } else { qsort(sin, 9, sizeof(char), cmp_d); } for (i = 0; i < 9; i++) { printf("%s\n", sin[i]); } return 0; }

  • C言語のクイックソートのプログラムについて

    こんにちは。 この質問のページを開いて頂き、ありがとうございます。 よろしければ、力になってください(..) C言語を独学で勉強しているのですが、 クイックソートのプログラムでひっかかり 次に進めない状況となっております。(>_<) 力をお貸しください..... あまり、ポインタ変数とか得意ではないので、分かりやすい説明を頂けましたら これからの勉強とかにも生かせると思うのでよろしくお願いします。 編集点だけでも教えて頂ければ幸いです。 プログラムの内容としては data1.txtの内容を読み込み、その内容を生年月日順に並び替えるというプログラムです。 若い人が一番上に来るように(つまり、生年月日の降順?で)作らなければなりません。 それに加えて、どのパターンを読み込んだかの順番も表示しなければなりません。 上記の日本語が分かりにくかったらすいません。 説明下手でもあるので(..) ちなみにdata1.txtの内容は 名前 身長 靴のサイズ 生年月日 となっております。 -----------data1.txtの内容------- A 164 24.0 19770926 B 168 24.5 19750801 C 166 24.0 19780228 D 162 23.0 19850914 E 172 24.5 19780904 F 168 24.5 19770605 G 164 24.0 19790621 H 156 23.0 19900919 I 160 24.5 19860330 J 170 26.0 19680614 --------data1.txtの内容 終わり------------ --------------------以下 C言語プログラム------------------- #include <stdio.h> #include <stdlib.h> /* 自己参照的構造体テンプレートの宣言 */ typedef struct node{ char name[25]; double shincyo; double shoe_size; int birth; struct node *next; }node_t; /* ノード割り当て関数 */ node_t *NodeAllocate(void) { node_t *p = (node_t *)malloc(sizeof(node_t)); /* (B)動的メモリ割り当て */ if(p == NULL){ fprintf(stderr,"\nERROR: Out of memory\n"); exit(1); } return p; } int main(void) { FILE *fpin; char fname[20] = "data1.txt"; int i, count = 0; int max; //最大値をチェックするための変数 int shoecount=0; double shoesize; /*靴サイズ入力・検索に用いる*/ node_t *start, *p, *pre_p, *q, *s, *temp; start = p = NodeAllocate(); /* (A)出力開始点初期化&動的メモリ割り当て */ /* 読み出しファイルオープン */ if((fpin = fopen(fname, "r")) == NULL){ printf("ファイルのオープンに失敗しました\n"); exit(1); } while(1){ /* End of File を読んだら while の無限ループを脱出 */ if(feof(fpin)) break; else{ /* 1行ずつ書式を指定して読み出す */ fscanf(fpin, "%s%lf%lf%d\n", p->name, &(p->shincyo), &(p->shoe_size), &(p->birth)); p->next = NodeAllocate(); /* (C)動的メモリ割り当て&リンク */ pre_p = p; p = p->next; /* (D)リンクポインタの更新 */ } } /* 読み出しファイルクローズ */ fclose(fpin); /* 読み込み結果出力 */ pre_p->next = NULL; printf("\n******* 入力データ画面の表示 *******\n"); for(p = start;p != NULL;p = p->next) printf("%s %3.1f %2.1f %d\n", p->name, p->shincyo, p->shoe_size, p->birth); printf("************************************\n\n"); /* 並び替え処理(選択法でソート) */ for(p=start; p->next!=NULL; p=p->next) { max = p->birth; s = p; for(q=p->next;q!=NULL;q=q->next) { count++; if(max < q->birth) { max = q->birth; s = q; } } if(p == start && s == p->next){ /*パターン1*/ temp = s->next; s->next = p; p->next = temp; start = s; p = s; pre_p = p; printf("パターン1-->"); } else if(p == start && s != p->next && s != p){ /*パターン2*/ temp = s->next; s->next = p; p->next = temp; start = s; p = s; pre_p = p; printf("パターン2-->"); } else if(p != start && s == p->next){ /*パターン3*/ temp = s->next; s->next = p; p->next = temp; p = s; pre_p = p; printf("パターン3-->"); } else if(p != start && s != p->next && s != p){ /*パターン4*/ temp = s->next; s->next = p; p->next = temp; p = s; pre_p = p; printf("パターン4-->"); } else{ /*パターン5*/ temp = s->next; s->next = p; p->next = temp; printf("パターン5-->"); } } printf("END"); /* 並び替え処理の結果出力 */ printf("\n******* 並び替え後のデータの表示 *******\n"); for(p = start;p != NULL;p = p->next) printf("%s %3.1f %2.1f %d\n", p->name, p->shincyo, p->shoe_size, p->birth); printf("************************************\n\n"); return 0; } ---------------------C言語プログラムの内容 終わり----------------- 私が間違っていると思っているのは パターン2とパターン4の条件文のとこが間違っているのかな?と思いますが・・・ 他にも間違っていてそれが原因であるならそこの点も教えてください。(>_<) よろしかったら 間違い部分の修正、説明 などよろしくお願いしたします。m(_ _)m

  • 連結リストによるデータ管理プログラムの解説

    ★から★までのプログラムが、各行ごとにどのような動きをしているのか簡潔な言葉で説明を書いていただきたいのです。必要がないと判断した行はとばして下さって構いません。 (例) printf("hello!"); …hello!と表示 if(a==0){ …aが0なら #include <stdio.h> #include <stdlib.h> struct CELL{ struct CELL *next; char data; }; /* Head CELL CELL CELL +-------+ +-------+ +-------+ +-------+ | ? | *----> | 5 | *----> | 6 | *----> | 8 | / | +-------+ +-------+ +-------+ +-------+ */ main(void){★ struct CELL head; struct CELL *p, *wp; char a; head.next=NULL; printf("?\n"); scanf("%c %*c",&a); while(a!='0'){ printf("mode?\n"); scanf("%c",&mode); if(mode=="a"){ p=&head; while(p->next!=NULL){ p=p->next; } wp=(struct CELL *)malloc(sizeof(struct CELL)); if(wp==NULL){ printf("cannot allocate enough memory.\n"); return 0; } p->next=wp; p->next->data=a; p->next->next=NULL; printf("?\n"); scanf("%c %*c",&a); } if(mode=="p"){ printf("\n\nNow...\n"); p=&head; while(p->next!=NULL){ printf("%c --> \n",p->next->data); p=p->next; } printf("NULL\n"); if(mode=="d"){ p=&head; while(p->next->data==a){ p=p->next; } if(p==NULL) break; wp=p->next->next; while(p->next->data==a) p=wp;★ } } return 0; }

  • c言語 片方向連結リスト

    c言語の片方向連結リストのプログラムについて質問があります. 下記のプログラムの関数int get_index(ListPtr l, int value)に以下のようなコードを書く.リストl において値value を持つセルの位置を返す.返り値は,最初のセルが値value を持っていれば0,次のセルが値value を持っていれば1,...,値value を持っているセルが存在しなければ–1とする. また,関数void add(ListPtr l, int index, int value)に以下のようなコードを書く.リストl の位置index に値value を持つセルを挿入.挿入前のリストに対して:index が0 のときは先頭に挿入,index が1 のときは(0から数えて)1番目のセルの前に挿入,index が2 のときは(0から数えて)2番目のセルの前に挿入,...,index がリストのサイズと等しいときはリストの末尾に挿入,それ以外の場合は何もしなくてよい. これらのコードはどのように書けばよいのでしょうか? #include <stdio.h> #include <stdlib.h> #include <assert.h> /* 連結リスト中のノードの構造体 */ struct node { int val; /* 値 */ struct node *next; /* 次ノード */ }; /* セルとそのポインタの型 */ typedef struct node Node; typedef Node *NodePtr; /* セルを一つ生成 */ NodePtr create_node(int v) { NodePtr n = NULL; n = malloc(sizeof(Node)); n->val = v; n->next = NULL; return n; } /* セルを表示 */ void print_node(NodePtr n) { if (n != NULL) { printf("<%d>", n->val); } else { printf("(null)"); } } /* 連結リストの構造体 */ struct list { /* 先頭セルへのポインタ */ NodePtr head; }; /* 連結リストとそのポインタの型 */ typedef struct list List; typedef List *ListPtr; /* 空の連結リストを生成 */ ListPtr create_list(void) { ListPtr l = NULL; l = malloc(sizeof(List)); l->head = NULL; return l; } /* 連結リスト l が空かどうか判定 */ int is_empty(ListPtr l) { return (l->head == NULL); } /* リスト l の内容を表示 */ void print_list(ListPtr l) { NodePtr n = NULL; if (is_empty(l)) { printf("(empty)\n"); return; } n = l->head; while (n != NULL) { print_node(n); n = n->next; } printf("\n"); } /* リスト l の先頭にセルを挿入 */ void add_first(ListPtr l, int val) { NodePtr n = NULL; n = create_node(val); n->next = l->head; l->head = n; } /* リスト l の先頭セルを削除 */ int delete_first(ListPtr l) { NodePtr n = NULL; int v; /* リストが空なら -1 を返す(負の値はリストに含まれないと仮定)*/ if (is_empty(l)) return -1; v = l->head->val; n = l->head; l->head = l->head->next; free(n); n = NULL; return v; } /* 連結リスト l のサイズを取得 */ int get_list_size(ListPtr l) { NodePtr n = NULL; int size; size = 0; n = l->head; while (n != NULL) { size++; n = n->next; } return size; } /* * 連結リスト l における index 番目のセルの値を取得 * (そのようなセルが存在しなければ -1 を返す) */ int get_value(ListPtr l, int index) { NodePtr n = NULL; if (index < 0) return -1; n = l->head; while (index > 0 && n != NULL) { n = n->next; index--; } return (n == NULL) ? -1 : n->val; } /* リスト l 中の全セルを削除(ループ版)*/ void delete_all(ListPtr l) { NodePtr n = NULL, m = NULL; n = l->head; while (n != NULL) { m = n; n = n->next; free(m); } l->head = NULL; } /* セル n 以降を全て削除(内部処理用の再帰関数)*/ void delete_rest(NodePtr n) { if (n->next != NULL) delete_rest(n->next); free(n); } /* リスト l 中の全セルを削除(再帰版)*/ void delete_all_recursively(ListPtr l) { if (l->head == NULL) return; delete_rest(l->head); l->head = NULL; } /* リスト l 全体を削除 */ #define delete_list(l) (delete_list0(l),l=NULL) void delete_list0(ListPtr l) { delete_all(l); free(l); } /* リスト l において値 val を持つセルの位置を返す */ int get_index(ListPtr l, int value) { return -1; } /* リスト l の位置 index に値 val を持つセルを挿入 */ void add(ListPtr l, int index, int value) { } /* 連結リストの使用例 */ int main(void) { FILE *fp = NULL; char buf[10]; int age; ListPtr l = NULL; l = create_list(); add_first(l, 28); add_first(l, 40); add_first(l, 33); add_first(l, 15); print_list(l); delete_first(l); print_list(l); delete_first(l); print_list(l); delete_first(l); print_list(l); delete_first(l); print_list(l); return 0; }

  • C言語 リスト

    (1) /* list.c */ #include <stdio.h> #include <stdlib.h> struct node { int num; struct node *next; }; main() { struct node *head, *p; int x; head = NULL; while(scanf("%d",&x) != EOF) { p = (struct node *)malloc(sizeof(struct node)); p->num = x; p->next = head; head = p; } // リストの要素のnumの値を先頭から順に表示する p=head; while(p!=NULL) { printf("%d\n" ,p->num); p = p->next; } } (2) struct node *q; q = head; while(q->next != NULL) q = q->next; (1)を(2)を使い新しいノードをリストの最後に追加するようにしたいのですが どう書いたら良いのか教えていただきたいです

  • リスト構造を使ってSortとSearchをするプログラム

    タイトルのとおりのプログラムを組んでみました ----------himajin.c----------- #include <stdio.h> #include <string.h> #include <stdlib.h> // 参考:http://www9.plala.or.jp/sgwr-t/c/sec15-5.html // コンパイラ:BCC 5.5 // アイテムの加え方が違う。 struct Item { int data; /* データ */ struct Item *next; /* 次のデータへのポインタ */ }; struct Item *head; struct Item *tail; struct Item *addItem(struct Item *p,int newdata){ struct Item *t; t->data = newdata; t->next = tail; p->next = t; return t; } int main(){ struct Item *item; int inputdata; head = item; item->next = tail; while (scanf("%d", &inputdata) != EOF) { item = addItem(item,inputdata); } /* search(5); sort(); */ return 0; } int sort(){ struct Item *j; struct Item *p; struct Item *t; p = head; t = head; while (p->next != tail){ while (p->data > t->data){ j = t; t = t->next; } j->next = p; p->next = t; p = p->next; } } int search(int searchdata){ struct Item *t; t = head; tail->data = searchdata; while (searchdata != t->data){ t = t->next; } if(t == tail){ printf("Not Found"); } else{ printf("Found"); /*後で考える*/ } return 0; } ---- ...が、コマンドラインで himajin.exe 5 と入力してみたところ、いきなりプログラムが落ちました。何がいけないのでしょうか?

  • C言語のプログラムの流れについて

    下に貼り付けたプログラムの流れを順番に教えて頂きたいです。 特にadd関数とinsert関数の中身の動きについてが分からないので教えていただきたいです。 (a,b,c,sentouなどの動きなど。) 参考にですが リスト構造を用いて、read関数で読み込んだ単語をアルファベット順にソートしてリストのセルに入れ、同じ単語はまとめてその単語と個数を順に表示するプログラムです。 1からの説明を要求して申し訳ありませんがよろしくお願いいたします。 #include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> typedef struct moji{ char w[50]; int cnt; struct moji *next; }moji; int main(){ FILE *fp; char data[50]; moji *sentou; moji *p=NULL; if((sentou=(moji *)malloc(sizeof(moji)))==NULL){ printf("malloc error\n"); exit(1); } fp=fopen("tango.txt","r"); if((fp = fopen("tango.txt","r"))==NULL){ printf("can't open\n"); exit(1); } while(read(data,fp)){ add(data,sentou); } p=sentou->next; while(p != NULL){ printf("%s %d\n",p->w,p->cnt); free(p); p=p->next; } fclose(fp); return (0); } int read(char data[],FILE *fp){ /*1つの単語(連続したアルファベット)をdataに格納して、スペースで区切られたらそこで格納をやめ、値1を返す。再度単語を格納するときはdataを初期化し、再度1つの単語を取得する。ファイルの単語がなくなれば(EOFなら)0を返す関数read()*/ } void add(char data[],moji *sentou){ moji *a,*c; for(c=sentou;c!=NULL;c=c->next){ if(strcmp(c->w,data)==0){ c->cnt++; return; } if(strcmp(c->w,data)>0){ break; } else{ a=c; } } insert(a,c,data); } void insert(moji *a,moji *c,char data[]){ moji *b; if((b=(moji *)malloc(sizeof(moji)))==NULL){ printf("malloc error\n"); exit(1); } strcpy(b->w,data); b->cnt=1; a->next=b; b->next=c; }

専門家に質問してみよう