我知道关于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;
}
答案 0 :(得分:5)
您正在覆盖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;
}