C中的升序链表

Ascending order Linked List in C

我的任务是实现一个将在项目中使用的插入函数。如果用户输入是 1 2 3 4,打印语句的期望输出将是 1、2、3、4。目前,我的打印语句返回 4、3、2、1,但我相信这是正确的。我认为我的问题出在我的输入函数中(它嵌套在一个 while 循环中以获取用户输入)。这是使用 C

如有任何帮助,我们将不胜感激。

struct set {

int    data; 
struct set* next_p;

};

struct set* getInput( struct set* head_p, int val ) {

    struct set* temp;

    temp->data   = val;
    temp->next_p = head_p;

    return temp;

} /* getInput */

struct set* makeSet( struct set* head_p ) {

    int val;

    printf( "Please enter a positive integer, or a negative to stop: \n" );

    scanf("%d", &val);

    while ( 100 ) {

        head_p = getInput( head_p, val );
        scanf("%d", &val);

    }

return head_p;

}
struct set* make_aSet(int val ) {
    struct set* temp;

    if((temp = malloc(sizeof(*temp))) != NULL){
        temp->data   = val;
        temp->next_p = NULL;
    } else {
        fprintf(stderr, "can't make new a set\n");
    }

    return temp;
}

struct set* makeSet(void) {
    struct set dummy_head, *current = &dummy_head;
    int val;

    printf( "Please enter a positive integer, or a negative to stop: \n" );

    while (1==scanf("%d", &val) && val >= 0 ) {
        current->next_p = make_aSet( val );
        current = current->next_p;
    }

    return dummy_head.next_p;
}

抱歉,伙计很忙,但嘿,我解决了你的问题 code.I 已经提到问题是你在头部之前附加了 newNode。

#include <stdio.h>
#include <stdlib.h>
struct set {

int    data;
struct set* next_p;

          };
struct set* getInput( struct set* ptr, int val )//appends a newNode to ptr which is the last node of Linked list
{

struct set* temp=NULL;
temp         = (struct set*)malloc(sizeof(struct set));
temp->data   = val;
temp->next_p = NULL;
if(ptr!=NULL)//if Linked list has been created,i.e.,only if we have a head run this
    ptr->next_p=temp;

return temp;

} /* getInput */

struct set* makeSet( struct set* head_p ) {

int val;
struct set* ptr=head_p;
printf( "Please enter a positive integer, or a negative to stop: \n" );
while (1) {

    scanf("%d", &val);
    if(val>=0)
        ptr=getInput( ptr, val );//appends only value>=0 to linked list else breaks from the infinite loop
    else
        break;

     if(head_p==NULL)//To set the head of the linked List! True only for the 1st node in the linked list
        head_p=ptr;

}

return head_p;

}
void display(struct set* head_p)
{
if(head_p==NULL)
    printf("\nno List in Memory\n"); //
else
{
struct set* ptr=head_p;
printf("\n the linked list is\nHead");
while(ptr!=NULL)
{
    printf("-->%d",ptr->data);
    ptr=ptr->next_p;
}
}
}
int main()
{
struct set* head_p=NULL;
head_p=makeSet((head_p));//returns the head of the linked list created
display(head_p);//displays the linked list
return 0;
}