我不确定我的写作是否正确。我的策略首先是按原点列表的第一个节点获得的,然后创建一个新的节点的新列表(在将原始列表的下一个节点放在head节点上(,然后迭代地每次获得第一个节点和链接。它是作为该列表的负责人到新的,相反的列表。这是我到目前为止所做的:
typedef struct node {
int data;
struct node *next;
} Node;
void reverseList(Node **head) {
Node *curr = *head; //
Node *new_node = *head;
Node *prev = NULL;
new_node->next = NULL; //the new list is to end with the first node of the origin list//
while (curr != NULL) { //traverse through the whole list//
curr = curr->next;
prev = curr; //getting the next first node//
prev->next = new_node; //and making it linked to the new list//
}
*head = new_node; //the new, reversed list//
}
您的代码中存在逻辑错误 -
观察代码段:
Node* new_node=*head;
Node* prev=NULL;
new_node->next=NULL;
第一行将new_node
设置为head
,而最后一行将next
的new_node
指针设置为NULL
。因此,有效地将head->next
设置为NULL
。结果,while循环最多一次。
在这里,我给您略微修改了reverseList
功能
void reverseList(Node** head)
{
Node* curr=*head;
Node *temp;
Node* prev=NULL;
while(curr!=NULL)
{
temp = curr->next; // keep track of the current nodes next node.
curr->next = prev; // reverse the link for the current node
prev=curr; // current node becomes the previous node for next iteration
curr=temp; // now the initially next node becomes the current node for next iteration
}
/*
After the end of the whiie loop, prev points to the last node.
So the change *head to point to the last node.
*/
*head = prev;
}