入门题目,不过挑战挺有意思的,如何不重新遍历就知道哪个点就是中点呢?
const middleNode = function (head) {
// write your code here
let slow = head;
let fast = head;
while(fast.next!==null && fast.next.next!==null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
做法很取巧,用一个辅助指针,每次向前进两个节点,如果这个指针走到最后了那就说明每次前进一个节点的指针正好走在了中点。
举一反三,移除倒数第N个节点,同样用两个指针,辅助指针指向主指针后的n个节点,如果该节点为null那么说明已经到达倒数第N个节点了。
const removeNthFromEnd = function (head, n) {
// write your code here
let slow = head;
let fast = head;
for(let i = 0;i<n;i++){
fast = fast.next;
}
if(fast){
while(fast.next!==null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
}else{
head = head.next;
}
return head;
}
网友评论