如何在C语言中正确反转单链表?
我从C开始,我被要求做一个链表,在它的节点数据中有随机整数,它们必须是上升顺序,然后我必须用一个函数颠倒顺序。我的问题是,在我的反向输出中,我只得到第一个数字,而它甚至没有反向如何在C语言中正确反转单链表?,c,data-structures,linked-list,C,Data Structures,Linked List,我从C开始,我被要求做一个链表,在它的节点数据中有随机整数,它们必须是上升顺序,然后我必须用一个函数颠倒顺序。我的问题是,在我的反向输出中,我只得到第一个数字,而它甚至没有反向 #include <stdio.h> #include <stdlib.h> int N; typedef struct node{ int num; struct node *next; }nodes; int first_node(nodes *head){ if(head == NUL
#include <stdio.h>
#include <stdlib.h>
int N;
typedef struct node{
int num;
struct node *next;
}nodes;
int first_node(nodes *head){
if(head == NULL){
printf("Error");
}
else{
head -> num= rand();
head->next=NULL;
}
}
int second_node(nodes *head){
nodes *uno=malloc(sizeof(nodes));
if(uno == NULL){
printf("Error");
}
else{
uno->num = rand();
uno->next = NULL;
if( uno->num>head->num){
head->next=uno;
}
else{
head= uno->next;
}
}
}
int insert_node(nodes *head){
nodes *dos=malloc(sizeof(nodes));
if(dos == NULL){
printf("Error");
}
else{
dos->num = rand();
dos->next = NULL;
nodes *current = head;
while(current!= NULL){
if(current->num<dos->num && current->next==NULL){
current->next = dos;
return;
}
else if (current->num<dos->num && current->next->num>dos->num){
dos->next=current->next;
current->next=dos;
return;
}
else if(head->num>dos->num){
dos->next=head;
head=dos;
}
current=current->next;
}
}}
void printnodes(nodes *head){
nodes *current = head;
while (current != NULL){
printf("%d\n",current->num);
current = current ->next;
}
}
void reverse(nodes *head)
{
nodes *a=head->next;
if(a!=NULL)
{
nodes *b=a->next;
a->next=head;
head->next=NULL;
head=a;
if(b!=NULL)
{
while(b!=NULL)
{
a=b;
b=b->next;
a->next=head;
head=a;
}
a->next=head;
head=a;
}
}
}
int main(){
printf("Insert the number of nodes u want to create:");
scanf("%d", &N );
nodes *head =malloc(sizeof(nodes));
int i =3;
if(N==1){
first_node(head);
}
else if (N ==2){
first_node(head);
second_node(head);
}
else if (N>2){
first_node(head);
second_node(head);
while(i<=N){
insert_node(head);
i++;
}
}
printnodes(head);
printf("\n\n Reversed \n\n");
reverse(head);
printnodes(head);
return 0;
}
创建5个节点时得到的输出为:
整齐:
41
3445
3890
8709
16777
反向:
41
我该如何解决这个问题呢?谢谢你,很抱歉你的英语不好,你的代码中有两个非常明显的问题: 第一个是赋值给局部变量,期望该赋值在函数返回后得到反映。我说的是你大部分职能部门的负责人。这里的问题是,当您将参数传递给函数时。它是按值传递的,这意味着它是复制的,并且您在调用的函数中拥有的只是一个副本或原始值。您应该知道,更改副本不会更改原件 快速浏览一下,我看到的第二个问题是第二个_节点函数,您首先要做的是
uno->next = NULL;
然后可能是
head= uno->next;
这将为head分配NULL
第一个问题很容易解决,通过模拟一种称为“按引用传递”的方法。我说的是模拟,因为C只有传递值。您可以使用指针在C中模拟按引用传递,这意味着要在C中按引用传递指针,必须向指针传递指针,如
int second_node(nodes **head){
...
}
*head = uno->next;
然后使用操作员的地址调用它:
second_node(&head);
然后在第二个节点中,使用解引用操作符*访问原始头指针,如
int second_node(nodes **head){
...
}
*head = uno->next;
在写上面的内容时,我注意到了第三个问题,那就是您将一些函数声明为返回int,但实际上并没有从函数中返回任何内容。谢天谢地,您似乎没有在任何地方使用返回值,但在应该返回值的函数中不返回值仍然是未定义的行为。如果不应从函数返回值,则必须将其声明为返回void:
通过调试反转,您发现了什么?此代码无法编译。你能发布必要的代码来重现这个问题吗?