19. 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:

1
2
3
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.

给定链表,移除倒数第n个值并返回链表

分析:移除倒数第n个值,为找到第n个值,必须先获得链表的长度,获得长度后,需要考虑是否会涉及到头链表的处理,如果移除的是头链表,则直接返回头链表的下一个节点,如果不是,则移除后直接返回头链表:

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

* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode temp = head;
int count = 0;
while (temp != null) {
count++;
temp = temp.next;
}
if (n == count) {
return head.next;
}
temp = head;
int cnt = 0;
while (cnt < count - n - 1) {
temp = temp.next;
cnt++;
}
temp.next = temp.next.next;
return head;
}
}