我正在尝试创建一个链接列表,该列表将从用户那里获取输入,对其进行排序,并在用户输入 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;
}
}