题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
这几个题用map来解都感觉变简单了,是不是属于逃课啊?
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
ListNode newHead = head;
if(head == null) return null;
if(head.next == null) return null;
HashMap<Integer, ListNode> map = new HashMap<>();
int length = 0;
for(int i = 0; head != null; head = head.next){
map.put(i, head);
length = i;
i++;
}
if(length - n + 1 == 0) return newHead.next;
ListNode pre = map.get(length - n);
ListNode node = map.get(length - n + 1);
pre.next = node.next;
return newHead;
}
}

