[英]I'm trying to add numbers into a linked list in ascending order. what can I fix so it'll work? Here's my code:
This code is supposed to put numbers into a linked list in ascending order. 此代码应按升序将数字放入链表中。 This is one function of my program that takes keyboard input(int x) from the user of the program.
这是我程序的一项功能,该功能从程序用户处获取键盘输入(int x)。
node* insert(node *head, int x)
{
node *newPtr;
node *prePtr;
node *currentPtr;
newPtr = malloc(sizeof(node));
if(newPtr != NULL){
newPtr->value = x;
newPtr->next = NULL;
prePtr = NULL;
currentPtr = head;
while(currentPtr != NULL && x > currentPtr->value){
prePtr = currentPtr;
currentPtr = currentPtr->next;
}
if(prePtr == NULL){
newPtr->next = head;
head = newPtr;
}
else{
prePtr->next = newPtr;
newPtr->next = currentPtr;
}
}
}
int main(void)//calling input function in main
{
node *head = NULL;
int x=0;
while(x!=-1){
printf("?: ");
scanf("%d", &x);
head=insert(head,x);
print(head);
printf("\n");
}
return 0;
}
//It seems to only put a few numbers in, then it resets
The main() function asks for a numerical input, and sends that input into the insert function which is supposed to put the numbers in ascending order. main()函数要求输入数字,然后将该输入发送到insert函数中,该函数应该将数字按升序排列。 Sample output:
样本输出:
$ gcc prelab2.c
$ ./a.out
?: 4
4 -> NULL
?: 3
3 -> 4 -> NULL
?: 9
3 -> 4 -> 9 -> NULL
?: 7
3 -> 4 -> 7 -> 9 -> NULL
?: 2
2 -> 3 -> 4 -> 7 -> 9 -> NULL
?: -1
There is only a small mistake. 只有一个小错误。 In main() method
在main()方法中
head=insert(head,x);
your Insert method return nothing (NULL). 您的Insert方法不返回任何内容(NULL)。 so your head is never changed it is always NULL;
因此,您的头永不改变,始终为NULL;
return head;
Just return head in insert method and it will work fine. 只需将头返回insert方法,它将正常工作。
Try the following changes it should work fine. 尝试以下更改,它应该可以正常工作。
node* insert(node *head, int x)
{
node *newPtr;
node *prePtr;
node *currentPtr;
newPtr = malloc(sizeof(node));
if(newPtr != NULL)
{
newPtr->value = x;
newPtr->next = NULL;
// check if the linked list is empty add the node directly and return
if(head == NULL)
{
head = newptr;
return head;
}
else
{
currentPtr = head;
while(x > currentPtr->value && currentPtr->next != NULL)
{
currentPtr = currentPtr->next;
}
// make the new node point where current next is pointing
newPtr->next = currentPtr->next;
// make the current point to new node
currentPtr->next = newPtr;
}
return head;
}
else
return NULL; // signifying malloc failed
}
EDIT: corrected the code missed out a condition check while copying 编辑:更正了代码,在复制时错过了条件检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.