簡體   English   中英

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;
}

對不起,隊友很忙,但是嘿,我修復了您的代碼。我已經提到過問題是您在頭之前附加了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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM