如何實現一個高效的單向鏈表逆序輸出?


問題:如何實現一個高效的單向鏈表逆序輸出?

出題人:阿里巴巴出題專家:昀龍/阿里雲彈性人工智能負責人

參考答案:下面是其中一種寫法,也可以有不同的寫法,比如遞歸等。

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<<"\t";
        tmp=tmp->next;
    }
}

 


今日一題選自GitHub項目 interview_internal_reference。

2019年最新總結,阿里,騰訊,百度,美團,頭條等技術面試題目,以及答案,專家出題人分析匯總。點擊「閱讀原文」即可 star 項目 interview_internal_reference。同樣關注訂閱號「Web項目聚集地」獲得每日面試題更新。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM