我的任务是实现一个将在项目中使用的插入函数。如果用户输入为1 2 3 4,则打印语句的所需输出将为1,2,3,4。目前,我的print语句返回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;
}
答案 0 :(得分:0)
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;
}
答案 1 :(得分:0)
对不起伙伴很忙,但是嘿我修复了你的代码。我已经提到问题是你在头部附加了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;
}