1. 程式人生 > >劍指offer-js編寫-鏈表

劍指offer-js編寫-鏈表

nehe 思想 comm push 宋體 this ext length mil

(1)輸入一個鏈表,從尾到頭打印鏈表每個節點的值。

思路:用一個數組來接收打印的鏈表,鏈表的結構已經給出。

/*function ListNode(x){

this.val = x;

this.next = null;

}*/

function printListFromTailToHead(head)

{

var arr=[];

while(head){

arr.unshift(head.val);

head=head.next;

}

return arr;

}

(2)

輸入一個鏈表,輸出該鏈表中倒數第

k個結點。

function FindKthToTail(head, k)

{

var arr=[];

while(head)

{

arr.push(head);

head=head.next;

}

if(arr.length==0 || k>arr.length){return false;}

return arr[arr.length-k];

}

(3)輸入一個鏈表,反轉鏈表後,輸出鏈表的所有元素。

思路:新建一個頭結點,遍歷原鏈表,把每個節點用頭結點插入到新建鏈表中。最後,新建的鏈表就是反轉後的鏈表。

function ReverseList(pHead)

{

var pre = null;

var next = null;

while(pHead){

next = pHead.next;

pHead.next = pre;

pre = pHead;

pHead = next;

}

return pre;

}

(4)輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。

function Merge(pHead1, pHead2)
{
if (pHead1 == null || pHead2 == null) {
return pHead1 || pHead2;
}

var head = null;

if (pHead1.val < pHead2.val) {
head = pHead1;
head.next = Merge(pHead2,pHead1.next)
}
else {
head = pHead2;
head.next = Merge(pHead1, pHead2.next);
}
return head;

}

(5)輸入一個復雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果為復制後復雜鏈表的head。

遞歸思想:把大問題轉化若幹子問題 此題轉化為一個頭結點和除去頭結點剩余部分,剩余部分操作和原問題一致

function RandomListNode(x){
this.label = x;
this.next = null;
this.random = null;
}
function Clone(pHead)
{
if(!pHead){
return null;
}
var CloneHead=new RandomListNode(pHead.label);
CloneHead.label=pHead.label;
CloneHead.random=pHead.random;

CloneHead.next=Clone(pHead.next);
return CloneHead;
}

劍指offer-js編寫-鏈表