如何实现一个高效的单向链表逆序输出?

问题:如何实现一个高效的单向链表逆序输出?

出题人:阿里巴巴出题专家:昀龙/阿里云弹性人工智能负责人

参考答案:下面是其中一种写法,也可以有不同的写法,比如递归等。

typedef struct node{
    int           data;
    struct node*  next;
    node(int d):data(d), next(NULL){}
}node;

void reverse(node* head)
{
    if(NULL == head || NULL == head->next){
        return;
    }
    
    node* prev=NULL;
    node* pcur=head->next;
    node* next;
    
    while(pcur!=NULL){
        if(pcur->next==NULL){
            pcur->next=prev;
            break;
        }
        next=pcur->next;
        pcur->next=prev;
        prev=pcur;
        pcur=next;
    }
    
    head->next=pcur;
    node*tmp=head->next;
    while(tmp!=NULL){
        cout<<tmp->data<<"	";
        tmp=tmp->next;
    }
}

今日一题选自GitHub项目 interview_internal_reference。

2019年最新总结,阿里,腾讯,百度,美团,头条等技术面试题目,以及答案,专家出题人分析汇总。点击「阅读原文」即可 star 项目 interview_internal_reference。同样关注订阅号「Web项目聚集地」获得每日面试题更新。

原文地址:https://www.cnblogs.com/williamjie/p/11131087.html