英文:
Linked List in order
问题
所以我们被给予一个数字数组,我们需要使用链表按顺序打印它们。
数组:19 2 3 13 124 6521 23 1 451 5 3123 412 354 13 13 23 13 1 45
但是我不明白为什么我的代码一直打印出45
。
我认为我已经正确地做了,但无论如何这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s node_t;
struct node_s
{
int n;
struct node_s *next;
};
node_t *new_element()
{
node_t *new;
new= malloc(sizeof(node_t));
if(new==NULL)
{
printf("Error");
exit(1);
}
return new;
}
node_t *list(node_t *head)
{
FILE *file;
file= fopen("file","r");
if(file==NULL)
{
exit(1);
}
int n;
node_t *new=NULL;
node_t *p=NULL;
new= new_element();
while (fscanf(file,"%d", &n)!=EOF)
{
new->n=n;
new->next=NULL;
if(head==NULL)
{
head=new;
}
else
{
p=head;
while (p->next!=NULL && p->next->n<new->n)
{
p=p->next;
}
new->next=p->next;
p->next=new;
}
}
return head;
}
void printList(node_t *head)
{
node_t *new=head;
while(new != NULL)
{
printf("%d-->",new->n);
new=new->next;
}
printf("NULL");
return;
}
int main() {
node_t *head=NULL;
head= list(head);
printList(head);
return 0;
}
基本上我尝试做的是,我们使用获取的数字创建一个新的节点。首先,我们检查列表是否为空。如果是,我们将新节点设置为头。
否则,我们比较数字,如果下一个节点的数字小于新节点的数字,我们更改指针。new
的next
指针指向链接的下一个节点,并且指向下一个节点的指针现在指向新节点。
至少我尝试实现了我说的。
英文:
So we have been given an array of numbers and we are required to print them out in order using linked lists
Array: 19 2 3 13 124 6521 23 1 451 5 3123 412 354 13 13 23 13 1 45
But i dont get why but my code keeps printing out 45
I think ive done it correctly but heres my code either way
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s node_t;
struct node_s
{
int n;
struct node_s *next;
};
node_t *new_element()
{
node_t *new;
new= malloc(sizeof(node_t));
if(new==NULL)
{
printf("Error");
exit(1);
}
return new;
}
node_t *list(node_t *head)
{
FILE *file;
file= fopen("file","r");
if(file==NULL)
{
exit(1);
}
int n;
node_t *new=NULL;
node_t *p=NULL;
new= new_element();
while (fscanf(file,"%d", &n)!=EOF)
{
new->n=n;
new->next=NULL;
if(head==NULL)
{
head=new;
}
else
{
p=head;
while (p->next!=NULL && p->next->n<new->n)
{
p=p->next;
}
new->next=p->next;
p->next=new;
}
}
return head;
}
void printList(node_t *head)
{
node_t *new=head;
while(new != NULL)
{
printf("%d-->",new->n);
new=new->next;
}
printf("NULL");
return;
}
int main() {
node_t *head=NULL;
head= list(head);
printList(head);
return 0;
}
Basically what i tried to do is. We create a new node with the acquired number. Firstly we check if list is empty or not. If it is we put the new node as the head.
Else we check the numbers, so if the number of the next node is lower than the number of the new node we change the pointers. The next
pointer of new
points to the next node of the link and the pointer that pointed to the next node now points to the new node.
At least i tried to implement what i said.
答案1
得分: 0
当我执行new=new_element();
时,我必须将它放在while循环中。
英文:
Ok nevermind i found a problem.
When i did the new=new_element();
i had to put that in the while loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论