C言語で頭の無い片方向循環リストを作成し、格納した整数の最大値を要素とする節点のうち最も後に現れた節点から順に、再び同じ節点に戻るまで、整数値を標準出力に出力するプログラムを作成していたのですが、最後尾から先頭に戻った時の先頭の数字の値が0になってしまいます。
どのようにすれば解決できるでしょうか?よろしくお願いします。
実現したいこと
最後尾から先頭に戻った時の先頭の数字の値を正常にする。
入出力例
1 3 5 2 4 >(5)(2)(4)(1)(3) 182 -8585 182 -17 182 -9999 >(182)(-9999)(182)(-8585)(182)(-17)
発生している問題
C
1>./a.out 21 33 45 52 64 7(5)(2)(4)(0)(1) 8> ./a.out 9182 10-8585 11182 12-17 13182 14-9999 15(182)(-9999)(0)(182)(-8585)(182)
該当のソースコード
C
1#include<stdio.h> 2#include<stdlib.h> 3 4typedef int elementtype; 5struct node { 6 elementtype element; 7 struct node* next; 8}; 9 10struct node list; 11 12void insert(int i){ 13 struct node* p; 14 struct node* next; 15 struct node* prev; 16 p=(struct node*)malloc(sizeof(struct node)); 17 p->element=i; 18 p->next=&list; 19 prev=&list; 20 for(next=list.next;next!=&list;next=next->next){ 21 prev=next; 22 } 23 prev->next=p; 24} 25 26void print_int_list(int c2) { 27 struct node* p; 28 struct node* q; 29 p=&list; 30 for(c2;c2>0;c2--){ 31 p=p->next; 32 } 33 q=p; 34 for(p;p->next!=q;p=p->next){ 35 printf("(%d)", p->element); 36 } 37 printf("\n"); 38} 39 40 41int main() { 42 int i,c2; 43 int c=0; 44 int n=-9999; 45 char buf[128]; 46 list.next=&list; 47 while (fgets(buf, sizeof(buf), stdin) != NULL) { 48 sscanf(buf,"%d",&i); 49 insert(i); 50 c++; 51 if(i>=n){ 52 n=i; 53 c2=c; 54 } 55 } 56 print_int_list(c2); 57 return 0; 58}
回答2件
あなたの回答
tips
プレビュー