C 带函数的反向链表
我试图通过将head节点传递给函数来反转和打印链接列表。然后,我必须使用“打印输出”功能打印反向列表。打印输出不是问题,但这种颠倒让我很难受。当我试图运行代码时,我只打印了两次列表C 带函数的反向链表,c,linked-list,C,Linked List,我试图通过将head节点传递给函数来反转和打印链接列表。然后,我必须使用“打印输出”功能打印反向列表。打印输出不是问题,但这种颠倒让我很难受。当我试图运行代码时,我只打印了两次列表 #include <stdio.h> #include <stdlib.h> typedef struct node { int number; struct node * next; } Node; typedef Node * Nodeptr; void printout
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int number;
struct node * next;
} Node;
typedef Node * Nodeptr;
void printout(Nodeptr);
int main()
{
int n;
Nodeptr head = NULL;
if((head = malloc(sizeof(Node))) == NULL)
return 0;
head->number = 72;
head->next = NULL;
Nodeptr here = head;
Nodeptr newnode = NULL;
for(n=0; n<100; n++)
{
if((newnode = malloc(sizeof(Node))) == NULL)
return 0;
newnode->number = rand()%50 + 50;
newnode->next = NULL;
here->next = newnode;
here = here->next;
//printf("value of cell %d contains %d\n", n, newnode->number);
}
printout(head);
//sum(head);
void reverse(head);
printout(head);
return 0;
}
void printout(Nodeptr head)
{
int i;
for(i=0; i<=100; i++)
{
if (head->next != NULL)
{
printf("value of cell %d contains %d \n",i, head->number);
head = head->next;
}
}
}
/*void sum(Nodeptr head)
{
int sum = 0;
do(sum += Nodeptr head);
while(head->next != NULL);
printf("Sum of nodes is %d \n", head->next);
}*/
void reverse(Nodeptr head)
{
Nodeptr current = head;
Nodeptr prev = NULL;
Nodeptr next = NULL;
int i;
while(current!=NULL)
{
//creating these to hold value while
//we reassign value to ptr's
next=current->next;
current->next=prev;
prev=current;
current=next;
}
head=prev;
}
我试图创建三个新节点来帮助我处理这里的指针。
希望这不是一个糟糕的问题,我感谢任何帮助。请注意,“打印输出”已注释掉,如果您希望自己测试此代码,则需要取消注释。顺便说一下,我正在使用代码块。再次感谢。主要问题是
reverse
还必须交换指向列表标题的指针。但是,使用函数void reverse(Nodeptr head)
,您可以按值传递head指针,因此没有机会以影响调用者的方式对其进行更改
我建议把签名改为
Nodeptr reverse(Nodeptr head);
并将呼叫更改为
head = reverse(head);
可能还有其他问题;但这可能是进一步分析的起点。0)void reverse(head)代码>-->void reverse(Nodeptr头);反向(头部)代码>1)head=prev
不更新调用方变量。2)如果(head->next!=NULL)
:关闭一个错误。
head = reverse(head);