文字列を記録するリストの問題
Posted: 2017年1月12日(木) 18:30
次の問題がわかりません。
(1)p->word=str_clone(word);
(2)if(head==tail){
head=tail=p;
}else{
tail->next=p;
tail=p;
}
(3)for(p=head;p!=NULL;p=p->next){
printf("%s\n",p-> word);
}
としたところcapacityしか表示されませんでした。
どなたか教えていただけると幸いです。
問題は読み込んだデータをアルファベット順にリストを使用して並び替えるというものです。
/* (1) */ から /* (3) */ の部分に適当なコードを書き込んで,プログラムを完成させよ.
読み込むデータ内容
definition
agriculture
background
account
creation
career
characteristic
anxiety
circumstance
ancestor
climate
alternative
crisis
decade
address
capacity
(1)p->word=str_clone(word);
(2)if(head==tail){
head=tail=p;
}else{
tail->next=p;
tail=p;
}
(3)for(p=head;p!=NULL;p=p->next){
printf("%s\n",p-> word);
}
としたところcapacityしか表示されませんでした。
どなたか教えていただけると幸いです。
問題は読み込んだデータをアルファベット順にリストを使用して並び替えるというものです。
/* (1) */ から /* (3) */ の部分に適当なコードを書き込んで,プログラムを完成させよ.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define L 256
/* リストを構成する自己参照構造体 */
typedef struct node {
char *word; /* 文字列を指すポインタ */
struct node *next;
} Node;
/* リストに記録されたデータを整列する関数 */
void mysort(Node *a)
{
char *x;
Node *p, *done = NULL;
while(done != a->next) {
for(p = a; p->next != done; p = p->next){
if(strcmp(p->word, p->next->word)>0) {
x = p->word;
p->word = p->next->word;
p->next->word = x;
}
}
done = p;
}
}
char *str_clone(char *s)
{
char *clone, *p;
int len;
len = strlen(s);
clone = p = (char*)malloc(sizeof(char)*(len+1));
strcpy(clone, s);
return clone;
}
int main(int argc, char *argv[])
{
FILE *ifp; /* 入力ファイル用ファイルポインタ */
char word[L]; /* ファイル読み込み用 char 配列 */
Node *head = NULL, *tail = NULL; /* リストの先頭と末尾を指すポインタ */
Node *p;
int i;
/* コマンドライン引数の数のチェック */
if(argc != 2) {
printf("使い方: %s 入力ファイル名\n", argv[0]);
exit(1);
}
/* 入力ファイルを開く */
if((ifp=fopen(argv[1],"r"))==NULL) {
printf("オープン失敗: \"%s\".\n", argv[1]);
exit(1);
}
/* 単語の読み込み */
for(i = 0; fscanf(ifp, "%s\n", word) > 0; i++) {
p = malloc(sizeof(Node)); /* Node の動的割り当て */
/* p->word が(str_cloneで作った) word の複製を指すようにする */
/* (1) */
/* リストの末尾に p の指す Node を追加 */
/* (2) */
}
tail->next = NULL; /* 末尾の Node の next を NULL に */
/* 入力ファイルを閉じる */
fclose(ifp);
/* 読み込んだ単語のソート */
mysort(head);
/* 単語を表示 */
/* (3) */
while(head != NULL) {
p = head->next;
free(head->word);
free(head);
head = p;
}
return 0;
}
definition
agriculture
background
account
creation
career
characteristic
anxiety
circumstance
ancestor
climate
alternative
crisis
decade
address
capacity