19. Remove Nth Node From End of List

"

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

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.

Note: Given n will always be valid.

Try to do this in one pass.

"

Solution:

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
31
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
Map<Integer, ListNode> map = new HashMap<Integer, ListNode>();
ListNode t = new ListNode(0);
t.next = head;
int i = 1;
while (t.next != null) {
map.put(i, t.next);
i++;
t = t.next;
}
if (head.next == null) {
return head.next;
} else if (!map.containsKey(i - n - 1)) {
head = map.get(i - n + 1);
} else if (!map.containsKey(i - n + 1)) {
map.get(i - n - 1).next = null;
} else {
map.get(i - n - 1).next = map.get(i - n + 1);
}
return head;
}
}

链表注意考虑既是头又是尾,头,尾,中间等情况