ユーザーからの入力を受け取り、注文し、ユーザーが0または負の数を入力すると印刷するリンクリストを作成しようとしています。私のコードのどこかで、印刷ループの先頭に「0」が追加されています。
例: 1-2-3-4-5 と入力します。次に、プログラムは 0-1-2-3-4-5 を返します。
例 2: 1-2-3-4-5 と入力します。次に、プログラムは 0-5-1-2-3-4 を返します。最終的にプログラムに入力値を最小から最大に順序付ける必要があるため、これも問題です。しかし、今のところ、入力 1-2-3-4-5 を取得して 1-2-3-4-5 を出力することに集中しています。
#include <stdio.h>
#include <stdlib.h>
struct listNode{
int data;
struct listNode *next;
};
//prototypes
void insertNode(struct listNode *Head, int x);
void printList(struct listNode *Head);
int freeList(struct listNode *Head, int x);
//main
int main(){
struct listNode Head = {0, NULL};
int x = 1;
printf("This program will create an odered linked list of numbers greater"
" than 0 until the user inputs 0 or a negative number.\n");
while (x > 0){
printf("Please input a value to store into the list.\n");
scanf("%d", &x);
if (x > 0){
insertNode(&Head, x);
}
}
printList(&Head);
system("PAUSE");
}
void insertNode(struct listNode * Head, int x){
struct listNode *newNode, *current;
newNode = malloc(sizeof(struct listNode));
newNode->data = x;
newNode->next = NULL;
current = Head;
while (current->next != NULL && current->data < x)
{
current = current->next;
}
if(current->next == NULL){
current->next = newNode;
}
else{
newNode->next = current->next;
current->next = newNode;
}
}
void printList(struct listNode * Head){
struct listNode *current = Head;
while (current != NULL){
if(current > 0){
printf("%d \n", *current);
}
current = current->next;
}
}