【刷算法】翻轉單鏈表的遞歸和非遞歸方法

題目描述

輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。面試

分析

典型的面試題以及大學數據結構課程常見題,沒啥好分析的了...數據結構

代碼實現

遞歸版

function ListNode(x){
    this.val = x;
    this.next = null;
}
function ReverseList(h)
{
    if(h === null || h.next === null)
        return h;
    
    var reversedHead = ReverseList(h.next);
    
    h.next.next = h;
    h.next = null;
    
    return reversedHead;
}

非遞歸版

function ListNode(x){
    this.val = x;
    this.next = null;
}
function ReverseList(h)
{
    if(h === null || h.next === null)
        return h;
    
    var pre = null;
    var cur = h;
    while(cur !== null) {
        var next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    
    return pre;
}
相關文章
相關標籤/搜索