連結リストに入力した「位置」に「アルファベット 1 文字」を挿入するプログラムを作成したのですが、入力した「位置」がリストの長さより大きい際、その後の入力した文字がリストの最後尾についてしまいます。どうすれば解決するでしょうか?
実行例
ink 0 L 42 d 4 e /入力終わり/ ink Link Linkd Linked
自分のプログラムの場合
ink 0 L 42 d 4 e ink Link Linkd Linkde <-
該当のソースコード
C
1#include <stdio.h> 2#include <stdlib.h> 3#include <string.h> 4 5typedef struct node* list; 6typedef char elementtype; 7struct node { 8 elementtype element; 9 struct node* next; 10}; 11 12struct node *initlist(elementtype e, struct node *x) { 13 struct node *n = (struct node *)malloc(sizeof(struct node)); 14 n->element = e; 15 n->next = x; 16 return n; 17} 18 19void insert(list *l, elementtype e) { 20 *l =initlist(e, *l); 21} 22 23void printlist(list l) { 24 for( ; l != NULL; l=l->next) printf("%c", l->element); 25 printf("\n"); 26} 27 28int main() { 29 char c,buf[128]; 30 int i, n; 31 struct node head; 32 list l = &head; 33 fgets(buf, sizeof(buf), stdin); 34 int len = strlen(buf); 35 if(len>0 && buf[len-1]=='\n') buf[len-1] = '\0'; 36 37 head.next = NULL; 38 for(i=strlen(buf)-1; i>=0; i--) { 39 insert(&head.next, buf[i]); 40 } 41 printlist(head.next); 42 43 while(fgets(buf,sizeof(buf),stdin) != NULL) { 44 sscanf(buf,"%d %c", &i, &c); 45 for(n=0; n<i && l->next!=NULL; n++, l=l->next); 46 insert(&l->next, c); 47 printlist(head.next); 48 } 49 50 return 0; 51} 52
補足情報(FW/ツールのバージョンなど)
unix gcc 4.8.5
回答3件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
こちらの回答が複数のユーザーから「質問に対する回答となっていない投稿」という指摘を受けました。