Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        去年关闭。
                                                                                            
                
        
我编写了一个代码,使用两个指针来反向链接列表。一次,我在2个节点之间反转1个指针。代码对我来说看起来不错。

Node* reverse(Node *head)
{
    Node *p = head;
    Node *q = p->next;
    Node *temp;
    while (q != NULL)   {
        temp = p;
        p = q->next;
        q->next = temp;

        temp = p;
        p=q;
        q=temp;
    }
    head = p;
    return p;
}


此处的逻辑错误是什么?

最佳答案

Node* reverse(Node *head)
{
    if(!head)
        return nullptr;
    Node *p = head;
    Node *q = p->next;
    p->next = nullptr;
    while(q != NULL)
    {
        Node *temp = q->next;
        q->next = p;
        p = q;
        q = temp;
    }
    head = p;
    return p;
}

08-17 05:44