给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
我的答案:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int num =0;
ListNode nextNode = head;
HashMap<Integer,ListNode> hashMap = new HashMap<>(100);
//遍历链表,放入hashMap
while(nextNode != null){
hashMap.put(num,nextNode);
num++;
nextNode = nextNode.next;
}
int size = hashMap.size();
//删除的节点是头节点,直接放回第二节点或者null
if (n == size){
return n==1 ? null : hashMap.get(1);
}
//获取被删节点的前一节点
nextNode = hashMap.get(hashMap.size()-n-1);
//指向被删节点的下一节点
if (n==1){
nextNode.next = null;
}else {
nextNode.next = hashMap.get(hashMap.size()-n+1);
}
return hashMap.get(0);
}
}
就是结果有点惨淡,明明是O(N)的复杂度:
官方答案:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode first = head;
ListNode second = dummy;
for (int i = 0; i < n; ++i) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
ListNode ans = dummy.next;
return ans;
}
}