每次我都不想接觸鏈表和樹的操作 這次要求逆轉鏈表結構(javascript) 核心思想是通過先存儲鏈表當前節點的next數據 let tt = tem.next; 使當前的節點的next指向我們設置的新鏈表(開始為null) tem.next = newhead; 更新新鏈表 newhead = t ...
每次我都不想接觸鏈表和樹的操作
鏈表結構 /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */
這次要求逆轉鏈表結構(javascript)
核心思想是通過先存儲鏈表當前節點的next數據 --------- let tt = tem.next;
使當前的節點的next指向我們設置的新鏈表(開始為null)---------------tem.next = newhead;
更新新鏈表 ---------------------newhead = tem;
更新舊鏈表準備下一次迴圈 ----------------------tem = tt;
1 /** 2 * @param {ListNode} head 3 * @return {ListNode} 4 */ 5 var reverseList = function(head) { 6 if(head === null){ 7 return null; 8 } 9 let newhead = null; 10 let tem = head; 11 while (tem != null){ 12 let tt = tem.next; 13 tem.next = newhead; 14 newhead = tem; 15 tem = tt; 16 } 17 return newhead; 18 };