鏈表反轉(Javascript)

//鏈表:無法通過下標遍歷,只能通過當前節點查找下一節點的鏈式結構

//構造鏈表節點
//this.val代表當前節點的值,this.next指向下一個節點,若this.next爲null(對象),則說明該節點爲鏈表的最後一個節點。
function Node(val) {
        this.val = val;
        this.next = null;
}

//定義鏈表
function list(arr) {
     this.head = null;
     var i,temp = null;
     while(i < arr.length){
         if(i === 0){
             //頭節點
             this.head = new Node(arr[i]);
         }else{
             //
             let newNode = new Node(arr[i]);
             temp.next = newNode;
             temp = temp.next;
         }
         i++;
     }

}

//鏈表反轉
var reverseList = function (head) {
    //pre結點可以用來反轉方向,爲了避免反轉之後鏈表斷開
    let pre = null;
    while(head){
       //先用next保存head的下一個結點信息,保證單鏈表不會斷裂;
        next = head.next;
        //讓head從指向next變成指向pre;
        head.next = pre;
        //到此,完成了pre到head的反轉,即pre<--head;

        //將pre,head,next依次向後移動一個結點。
        pre = head;
        head = next;
    }
    //如果head爲null的時候,pre就爲最後一個節點了,但是鏈表已經反轉完畢,pre就是反轉後鏈表的第一個節點
    //直接輸出pre就是我們想要得到的反轉後的鏈表
    return pre ;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章