問題形貌
輸入一個鏈表,反轉鏈表后,輸出新鏈表的表頭。
剖析
典範的面試題以及大學數據結構課程罕見題,沒啥好剖析的了…
代碼完成
遞歸版
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;
}