Given a linked list, remove the nth node from the end of list and return its head.
Note: The solution set must not contain duplicate quadruplets.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
- 題目大意
給定一個(gè)單向鏈表,移除單向鏈表的倒數(shù)第n個(gè)唧瘾。
比較簡(jiǎn)單挠锥,我的做法是將單向鏈表變成雙向鏈表帆啃,找到最后一個(gè)策幼,然后倒著找到倒數(shù)第n個(gè)節(jié)點(diǎn)并刪除摊唇。 注意一些邊界情況。
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
const removeNthFromEnd = function (head, n) {
let pointer = head;
while (pointer.next) {
pointer.next.last = pointer; //遍歷狐胎,使其變?yōu)殡p向鏈表
pointer = pointer.next;
}
let i = 1;
while (i < n) {
pointer = pointer.last; //找到倒數(shù)第n個(gè)節(jié)點(diǎn)
i++;
}
if (pointer === head) { // 如果是head鸭栖,直接將head向后移一個(gè)指針
head = head.next;
} else {
pointer.last.next = pointer.next;
}
return head;
};