Toc
  1. Remove Nth Node From End of List
  2. Example:
  3. Note:
  4. Ans:
Toc
0 results found
bbcfive
Remove Nth Node From End of List
2019/08/25 Algorithm List 双指针

Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

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.

Note:

Given n will always be valid.

Ans:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
var temp = head;
for (let i = 0; i < n; i++) {
temp = temp.next;
}

if(!temp) return head.next; // n equals list.length

var cur = head;
while(temp.next) {
temp = temp.next;
cur = cur.next;
}

cur.next = cur.next.next;

return head;
};

又是令人头秃的一天~

本文作者:bbcfive
版权声明:本文首发于bbcfive的博客,转载请注明出处!