19. 删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
解法
快慢指针
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null){
return null;
}
ListNode fast = head;
ListNode slow = head;
int step = 0;
while(fast.next != null){
fast = fast.next;
if (step < n){
step ++;
}else {
slow = slow.next;
}
}
// 判断是不是删除头结点
if (step == n){
slow.next = slow.next.next;
return head;
}
return head.next;
}
if…else…在leetcode应该会影响到执行用时
在结果处使用以下代码 会增加用时
ListNode res =null;
// 判断是不是删除头结点
if (step == n){
slow.next = slow.next.next;
return head;
}else {
res = head.next;
}
return res;