题目描述:
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
解题思路:
1.要想删除链表的倒数第N个节点,需要遍历链表得出长度。
2.然后将第length-n的下一节点指向下下个节点即可。
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
let cur = head,length=0;
while(cur != null){
cur = cur.next;
length++;
}
if(length == n){
return head.next;
}
cur = head;
let temp = length - n;
while(temp>1){
cur = cur.next;
temp--;
}
cur.next = cur.next.next;
return head;
};