teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

修正しました

2021/02/06 06:56

投稿

katkey
katkey

スコア15

title CHANGED
File without changes
body CHANGED
@@ -3,6 +3,7 @@
3
3
  1番目は要素数となっており、:より右側の数字が1つ1つの要素となっています。
4
4
  自分の考えとしては、fgetcで要素数を変数kに代入し、その後の要素をfgetsでまとめてbufに代入すればよいと考えたのですが、kの値を見るとうまく代入されていないようです。その後のbufの値も表示されません。
5
5
  これは何が原因なのでしょうか。分かる方いましたら、回答をお願いします。
6
+ このプログラム自体は単方向リストを用いて、要素の中でかぶっていないものを昇順に表示するものとなっています。
6
7
 
7
8
  ### 表示結果
8
9
 
@@ -13,7 +14,70 @@
13
14
  ### 該当のソースコード
14
15
 
15
16
  ```c
17
+ #include<stdio.h>
18
+ #include<stdlib.h>
19
+
20
+ #define MAX 256
21
+
22
+ typedef struct LISTNODE
23
+ {
24
+ int data;
25
+ struct LISTNODE *pNext;
26
+ struct LISTNODE *pPrev;
27
+ }ListNode;
28
+
29
+ ListNode head;
30
+
31
+ ListNode* getNode(int num){
32
+ int i;
33
+ ListNode *retNode=&head;
34
+
35
+ for(i=0;i<num;i++){
36
+ retNode=retNode->pNext;
37
+ if(retNode==NULL){
38
+ return 0;
39
+ }
40
+ }
41
+ return retNode;
42
+ }
43
+
44
+ int checkNode(int num1){
45
+ ListNode *currentNode, *pCheckNode=getNode(num1);
46
+ currentNode=head.pNext;
47
+ while(currentNode!=pCheckNode){
48
+ if(currentNode->data>pCheckNode->data)
49
+ return 1;
50
+ currentNode=currentNode->pNext;
51
+ }
52
+ return 0;
53
+ }
54
+
55
+ int swapNode(int num1, int num2){
56
+ ListNode *node1=getNode(num1), *node2=getNode(num2);
57
+ ListNode *tmpNext, *tmpPrev;
58
+
59
+ if(node1->pNext!=node2){
60
+ tmpNext=node1->pNext;
61
+
62
+ node1->pNext=node2->pNext;
63
+ node1->pPrev->pNext=node2;
64
+ node2->pPrev->pNext=node1;
65
+ node2->pNext=tmpNext;
66
+ }else{
67
+ node1->pPrev->pNext=node2;
68
+ node1->pNext=node2->pNext;
69
+ node2->pNext=node1;
70
+ }
71
+ return 1;
72
+ }
73
+
74
+ int addNode(){
75
+ int k,c;
76
+ ListNode *currentNode=head.pNext;
77
+ ListNode *newNode, *pCheckNode, *pNextNode;
78
+ newNode=(ListNode*)malloc(sizeof(ListNode));
79
+
16
- FILE *fp=fopen("test1.txt","r");
80
+ FILE *fp=fopen("test1.txt","r"); //問題の部分
17
81
  k=fgetc(fp);
18
82
  printf("k=%d\n",k);
19
83
  char buf[k];
@@ -31,6 +95,42 @@
31
95
  pPrevNode=pPrevNode->pNext;
32
96
  }
33
97
  }
98
+
99
+ fclose(fp);
100
+
101
+ int nodeNum;
102
+ ListNode *pEndNode=getNode(c);
103
+ while(head.pNext!=pEndNode){
104
+ pCheckNode=head.pNext;
105
+ nodeNum=0;
106
+ while(pCheckNode->pNext!=NULL){
107
+ pNextNode=pCheckNode->pNext;
108
+ nodeNum++;
109
+ if(pCheckNode->data>pNextNode->data)
110
+ swapNode(nodeNum, nodeNum+1);
111
+ else
112
+ pCheckNode=pCheckNode->pNext;
113
+ }
114
+ pEndNode=pEndNode->pPrev;
115
+ }
116
+
117
+ printf("<");
118
+ for(;currentNode!=NULL;){
119
+ if(currentNode->pNext==NULL)
120
+ printf("%d>",currentNode->data);
121
+ else
122
+ printf("%d, ",currentNode->data);
123
+ currentNode=currentNode->pNext;
124
+ }
125
+ printf("\nNumber of elements: %d",c);
126
+
127
+ return 1;
128
+ }
129
+
130
+ int main(void){
131
+ addNode();
132
+ return 0;
133
+ }
34
134
  ```
35
135
  ###test1.txt
36
136
  ```c