我正在尝试编写一个通过引用反转链表的函数

时间:2017-06-25 10:53:48

标签: c linked-list

我不确定我写的是不对的。我的策略是首先通过原始列表的第一个节点获取并创建一个节点的新列表(同时将原始列表的下一个节点设置为头节点),然后通过迭代获取每次第一个节点和链接通过成为该列表的负责人,它成为新的,颠倒的列表。以下是我到目前为止所做的事情:

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//
}

1 个答案:

答案 0 :(得分:1)

您的代码中存在逻辑错误 -
观察代码段:

Node* new_node=*head;    
Node* prev=NULL;

new_node->next=NULL;

第一行将new_node设置为head,而最后一行将next指针设置为new_nodeNULL。因此,实际上您将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; 

}