链表常用思路
Opened this issue · 0 comments
lovelmh13 commented
找链表的中间值
用快慢指针
function findMid (head) {
let slow = head
let fast = head
while (fast.next && fast.next.next) {
slow = slow.next
fast = fast.next.next
}
const newHead = slow.next // 后半段拆出来
slow.next = null // 将链表切断,把前半段拆出来
return newHead // 后半段是 newHead,前半段是 head
}
反转链表
画个图就懂了
function reverseList (head) {
let initHead = head
let pre = head
while (initHead && initHead.next) {
const node = initHead.next
initHead.next = initHead.next.next
node.next = pre
pre = node
}
return pre
}