📜  数据结构 |链表 |问题 5

📅  最后修改于: 2021-09-08 14:57:00             🧑  作者: Mango

下面的函数reverse() 应该反转一个单链表。函数末尾缺少一行。

/* Link list node */
struct node
{
    int data;
    struct node* next;
};
  
/* head_ref is a double pointer which points to head (or start) pointer 
  of linked list */
static void reverse(struct node** head_ref)
{
    struct node* prev   = NULL;
    struct node* current = *head_ref;
    struct node* next;
    while (current != NULL)
    {
        next  = current->next;  
        current->next = prev;   
        prev = current;
        current = next;
    }
    /*ADD A STATEMENT HERE*/
}
  

应该添加什么来代替“/*ADD A STATEMENT HERE*/”,以便函数正确反转链表。
(A) *head_ref = prev;
(B) *head_ref = 当前;
(C) *head_ref = 下一个;
(D) *head_ref = NULL;答案:(一)
解释: *head_ref = prev;

在while循环结束时, prev指针指向原始链表的最后一个节点。我们需要更改 *head_ref 以便头指针现在开始指向最后一个节点。

请参阅以下完整的运行程序。

#include
#include
   
/* Link list node */
struct node
{
    int data;
    struct node* next;
};
   
/* Function to reverse the linked list */
static void reverse(struct node** head_ref)
{
    struct node* prev   = NULL;
    struct node* current = *head_ref;
    struct node* next;
    while (current != NULL)
    {
        next  = current->next;  
        current->next = prev;   
        prev = current;
        current = next;
    }
    *head_ref = prev;
}
   
/* Function to push a node */
void push(struct node** head_ref, int new_data)
{
    /* allocate node */
    struct node* new_node =
            (struct node*) malloc(sizeof(struct node));
              
    /* put in the data  */
    new_node->data  = new_data;
                  
    /* link the old list off the new node */
    new_node->next = (*head_ref);    
          
    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}
   
/* Function to print linked list */
void printList(struct node *head)
{
    struct node *temp = head;
    while(temp != NULL)
    {
        printf("%d  ", temp->data);    
        temp = temp->next;  
    }
}    
   
/* Drier program to test above function*/
int main()
{
    /* Start with the empty list */
    struct node* head = NULL;
     
     push(&head, 20);
     push(&head, 4);
     push(&head, 15); 
     push(&head, 85);      
       
     printList(head);    
     reverse(&head);                      
     printf("\n Reversed Linked list \n");
     printList(head);    
     return 0;
}