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.
- 題目大意
給定一個單向鏈表,移除單向鏈表的倒數(shù)第n個。
比較簡單,我的做法是將單向鏈表變成雙向鏈表,找到最后一個,然后倒著找到倒數(shù)第n個節(jié)點并刪除。 注意一些邊界情況。
/**
* 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個節(jié)點
i++;
}
if (pointer === head) { // 如果是head,直接將head向后移一個指針
head = head.next;
} else {
pointer.last.next = pointer.next;
}
return head;
};