刚刚对其进行了一些编辑,我尝试了您所说的但它没有用,所以我尝试了一些我更熟悉的东西,但它似乎无法正常工作。它奇怪地打印信息然后崩溃.. 例如:当我输入 9-8-7-6-5-4-3-2-1 然后 0 打印时,它会打印回我 0-0-0-9- 1-2-3-4-5-6-7-8 然后崩溃?当我输入 1-2-3-4-5-6-7-8-9 然后 0 打印时,它会打印回我 0-0-0-1-2-3-4-5-6-7- 8-9然后崩溃。
#include <stdio.h>
#include <stdlib.h>
struct listNode{
int data; //ordered field
struct listNode *next;
};
//prototypes
void insertNode(struct listNode *Head, int x);
int printList(struct listNode *Head);
int freeList(struct listNode *Head, int x);
//main
int main(){
struct listNode Head = {0, NULL};
int x = 1;
int ret = 0;
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);
insertNode(&Head, x);
}
ret = printList(&Head);
}
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;
}
}
int printList(struct listNode * Head){
struct listNode *current = Head;
while (Head != NULL){
printf("%d \n", *current);
current = current->next;
}
}