我知道在SO上同一问题有多个问题。但是在某个地方,我无法理解逻辑。
倒转链表的函数如下:
void reverse()
{
struct node *curr=head, *prev=NULL;
while(curr!=NULL)
{
curr->next = prev;
prev = curr;
curr = curr->next;
}
head = prev;
}
我使用全局头指针和链表中节点的结构是:
struct node
{
int data;
struct node *next;
};
struct node *head = NULL;
在这里,每次curr
节点都指向prev
节点,最后当curr
节点遍历列表时,prev
节点将指向列表中的最后一个节点,我将其作为头指针。
但是,这个逻辑不会反转列表,而只打印第一个节点。所以,我认为代码只执行了一次,但我无法捕捉到错误。
使程序完整的其他功能:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head = NULL;
void add(int n)
{
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->data = n;
temp->next = NULL;
if(head == NULL)
{
head = temp;
return;
}
temp->next = head;
head = temp;
}
void print()
{
struct node *temp = head;
printf("n The List is : ");
while(temp!=NULL)
{
printf(" %d ",temp->data);
temp = temp->next;
}
}
void reverse()
{
struct node *curr=head, *prev=NULL;
while(curr!=NULL)
{
curr->next = prev;
prev = curr;
curr = curr->next;
}
head = prev;
}
int main(void)
{
add(1);
add(2);
add(3);
add(4);
add(5);
print();
reverse();
print();
return 0;
}
您正在覆盖curr->next
指针,该指针随后用于迭代列表。代码应该更像这样:
void reverse()
{
struct node *curr=head, *prev=NULL;
struct node *next;
while(curr!=NULL)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
}