【问题标题】:I am trying to write a function which reverses a linked list by reference [duplicate]我正在尝试编写一个通过引用反转链表的函数[重复]
【发布时间】:2017-11-28 11:04:09
【问题描述】:

我不确定我写的是否正确。我的策略是首先获取原始列表的第一个节点,然后创建一个节点的新列表(同时使原始列表的下一个节点成为头节点),然后每次迭代获取第一个节点和链接通过成为该列表的负责人,将其添加到新的反向列表中。这是我到目前为止所做的:

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

【问题讨论】:

  • 您是否尝试过检查自己的代码是否正确?
  • 在开始循环之前,您将head->next 设置为NULL,这样while 循环将只运行一次。
  • 我没有设置head->在NULL旁边...
  • new_nodehead 由于Node* new_node=*head;new_node->next=NULL; 行将head->next 设置为NULL
  • 我该如何解决?

标签: c linked-list


【解决方案1】:

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

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

new_node->next=NULL;

第一行将new_node 设置为head,而最后一行将new_nodenext 指针设置为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; 

}

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多