var reverseList = function(head) { if(!head){ // 这个判断多余了 return head } let prev = null // 这个利用了哨兵,简化了判断 while(head){ // 判断条件很重要 const next = head.next head.next = prev if(!next){ return head } prev = head head = next } return head // return pre 就不用判断next了 };
优秀代码
1 2 3 4 5 6 7 8 9 10 11
var reverseList = function (head) { var pre = null, cur = head, next; while (cur) { // 用cur取代head 迭代过程更加清晰 next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; };
少了两步判断,注意细节
递归方法
自己的代码
条件重复了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var reverseList = function(head) { if(!head){ // 这个其实和下边的条件重复了 return head } return df(null, head) function df(prev, cur){ if(!cur){ return prev }else{ const next = cur.next cur.next = prev return df(cur, next) } } };
优秀代码
1 2 3 4 5 6 7 8 9 10 11 12
var reverseList = function (head) { function df(pre, cur) { if (cur === null) { return pre; } else { var temp = cur.next; cur.next = pre; return df(cur, temp); } } return df(null, head); };
单参数递归-==需要重点理解==
可以被称为前置递归,而上边那种可以叫做后置递归
这种递归处理 从尾部开始处理,一步步向头部靠近,不太容易理解,需要重点关注
1 2 3 4 5 6 7 8 9 10 11 12
var reverseList = function (head) { function df(head) { if (!head || head.next === null) { return head; } const last = df(head.next) head.next.next = head head.next = null return last } return df(head); };
var reverseBetween = function(head, left, right) { const dmNode = new ListNode(-1, head) let cur = dmNode let pre = null let leftNode = null let index = 0 while(cur){ if(index === right+1){ break; } if(index===left-1){ leftNode = cur pre = cur.next
cur = cur.next }else if(index > left){ const leftNodeNext = leftNode.next pre.next = cur.next leftNode.next = cur cur.next = leftNodeNext cur = pre.next }else{ cur = cur.next } index++ } return dmNode.next };
var reverseBetween = function(head, left, right) { // 设置 dummyNode 是这一类问题的一般做法 const dummy_node = new ListNode(-1); dummy_node.next = head; let pre = dummy_node; for (let i = 0; i < left - 1; ++i) { pre = pre.next; }
let cur = pre.next; for (let i = 0; i < right - left; ++i) { const next = cur.next; cur.next = next.next; next.next = pre.next; pre.next = next; } return dummy_node.next; };
var isPalindrome = function (head) { let left = right = head; let flag = true function df(head){ if(!head){ return head } df(head.next) if(head.val !== left.val){ flag = false return } left = left.next } df(right) return flag };
const getIntersectionNode = (A, B) => { let pA = A, pB = B; while (pA !== pB) { pA = pA === null ? B : pA.next; pB = pB === null ? A : pB.next; } return pA; };