如果不小心网友来到了这里请网友自动飘走,浪费你们时间表示歉意。该系列博客的目的是:想作为自律工具和朋友一起每天刷几道题作为打卡督促的功能,没有什么可参考学习的东西,也不是刷博客量充大佬的目的
题号:160
//map解法
var getIntersectionNode = function (headA, headB) {
let map = new Map()
while (headA) {
if (map.has(headA)) {
let num = map.get(headA)
num++
map.set(headA,num)
} else {
map.set(headA,1)
}
headA = headA.next
}
while (headB) {
if (map.has(headB)) {
return headB
} else {
map.set(headB,1)
}
headB = headB.next
}
};
//双指针
var getIntersectionNode = function (headA, headB) {
let l1 = headA, l2 = headB
//l1和l2只要相等就找到相交节点了
while (l1 != l2) {
//l1 l2总有一个先到头,到头之后把其指向另一个链表头部
//这样等另一个长的链表也到头指向短的链表头部的时候
//那个先到头的指针l1或者l2已经走了一个长-短的差值
//后到到头的l1或者l2此时在链表头部,此时继续遍历
//总能使l1和l2一起到头找到交汇处
if (l1 == null) {
//发现l1到头了
l1 = headB
} else {
l1 = l1.next
}
if (l2 == null) {
//发现l2到头了
l2 = headA
} else {
l2 = l2.next
}
}
return l1
};
题号:234
//双指针
var isPalindrome = function (head) {
if (head == null || head.next == null) {
return true
}
//快慢指针找中点
let fast = head, slow = head
while (fast.next && fast.next.next) {
fast = fast.next.next
slow = slow.next
}
let l1 = null, l2 = null, tail = null
if (fast.next) {
//偶数个节点
l1 = head
l2 = fast.next
} else {
//奇数个节点
l1 = head
l2 = fast
}
//翻转链表
helper(slow.next)
//比较
while (l2) {
if (l2.val != l1.val) {
return false
} else {
l1 = l1.next
l2 = l2.next
}
}
return true
};
function helper(list) {
if (list.next == null) {
return list
} else {
let curNode = list
let node = helper(list.next)
node.next = curNode
curNode.next = null
return curNode
}
}
//递归很巧妙
//用一个全局变量保存从头开始遍历head节点的位置
//递归栈的特性,逆序访问节点然后和全局保存的从头开始的
//的节点的值是否相等
let globalVal = null
var isPalindrome = function (head) {
globalVal = head
return helper(head)
};
function helper(list) {
if (list == null) {
return true
}
let result = helper(list.next) && globalVal.val == list.val
globalVal = globalVal.next
return result
}