给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
1 /** 2 * Defination for singly-linked list 3 * function ListNode(val,next){ 4 * this.val=(val===undefined?0:val) 5 * this.next=(next===undefined?null:next) 6 * } 7 */ 8 /** 9 * @param {ListNode} head 10 * @param {number} n 11 * @return {ListNode} 12 */ 13 14 var removeNthFromEnd = function(head, n) { 15 let dummy = new ListNode(); 16 dummy.next = head; 17 let n1 = dummy; 18 let n2 = dummy; 19 for (let i = 0; i <= n; i++) { 20 n2 = n2.next; 21 } 22 while (n2 !== null) { 23 n1 = n1.next; 24 n2 = n2.next; 25 } 26 n1.next = n1.next.next; 27 return dummy.next; 28 };
标签:head,ListNode,val,19,结点,next,链表,倒数第 From: https://www.cnblogs.com/icyyyy/p/16851139.html