两两交换链表中的节点
题目链接:两两交换链表中的节点
- 思路:定义虚拟头节点,定义2个中间temp变量保存next值,不断遍历交换节点
var swapPairs = function(head) {
const ret = new ListNode(0, head)
let pre = ret, temp1 = null, temp2 = null
while(pre.next && pre.next.next) {
temp1 = pre.next
temp2 = pre.next.next.next
pre.next = pre.next.next
pre.next.next = temp1
pre.next.next.next = temp2
pre = temp1
}
return ret.next
};
删除链表的倒数第N个节点
题目链接:删除链表的倒数第N个节点
- 思路:倒数第n个节点已知,先定义虚拟表头,利用快慢指针,让fast先走n + 1步,然后fast & slow一起遍历,当fast指向null的时候,slow的下一个next为需要删除的节点
var removeNthFromEnd = function(head, n) {
const ret = new ListNode(0, head)
let fast = slow = ret
fast = fast.next
while(n--) {
fast = fast.next
}
while(fast) {
fast = fast.next
slow = slow.next
}
slow.next = slow.next.next
return ret.next
};
链表相交
题目链接:链表相交
- 思路:先获取2个链表的长度,然后相减得到len,先让headA先走len,然后再一起遍历
var getIntersectionNode = function(headA, headB) {
const getLen = (head) => {
let len = 0, cur = head
while(cur) {
len++
cur = cur.next
}
return len
}
let lenA = getLen(headA), lenB = getLen(headB)
if(lenA < lenB) {
[lenA, lenB] = [lenB, lenA];
[headA, headB] = [headB, headA]
}
let curA = headA, curB = headB
let len = lenA - lenB
while(len--) {
curA = curA.next
}
while(curA) {
if(curA === curB) {
return curA
}
curA = curA.next
curB = curB.next
}
return null
};
环形链表2
题目链接:环形链表2
- 思路:先找出fast & slow指针相遇节点,然后遍历
var detectCycle = function(head) {
if(!head || !head.next) return null
let slow = head.next, fast = head.next.next
while(fast && fast.next && fast !== slow) {
slow = slow.next
fast = fast.next.next
}
if(!fast || !fast.next) return null
slow = head
while(fast !== slow) {
slow = slow.next
fast = fast.next
}
return slow
};