题目来源:leetcode
题目描述:
给你一个链表,删除链表的倒数第
n
个结点,并且返回链表的头结点。进阶:你能尝试使用一趟扫描实现吗?
这里,仅给出一趟扫描的两种解法 :缓存、双指针
解法1:通过缓存,实现一趟扫描
public ListNode removeNthFromEnd(ListNode head, int n) {
Map<Integer, ListNode> map = new HashMap();
int count = 0; // 到最后,便是整个链表的长度
ListNode cur = head;
while(cur!=null){
count++;
map.put(count, cur);
cur = cur.next;
}
if(count-n<0){
return null;
}
// 第一个
if(count-n==0){
head = head.next;
return head;
}
// 最后一个
if(n==1){
ListNode nthNode = map.get(count-n);
nthNode.next = null;
return head;
}
// 第n个的前一个
ListNode nthNode = map.get(count-n);
// 第n个的后一个
nthNode.next = map.getOrDefault(count-n+2, null);
return head;
}
解法2:双指针法
public ListNode removeNthFromEnd(ListNode head, int n) {
// 双指针:保持步长差距为n
ListNode dummy = new ListNode();
dummy.next = head;
ListNode pre = dummy, pos = dummy;
int step = 0;
while(pre!=null){
if(step > n){
pos = pos.next;
}
pre = pre.next; // pre的移动放在pos的后面,否则出现多一轮移动的情况
step++;
}
// 第一个节点
if(pos == dummy){
head = head.next;
return head;
}
// 最后一个节点
if(pos.next == pre){
pos.next = null;
return head;
}
// 中间节点
pos.next = pos.next.next;
return head;
}