题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
//先找到倒数第n个节点
ListNode f = head;
ListNode s = head;
while(n>0){
if(f!=null){
f = f.next;
}//此题不用考虑n大于链表长度
n--;
}
ListNode pre = new ListNode(0);
pre.next = s;
if(f==null){
//此时说明删除的是头节点,因为n最多等于链表长度
return head.next;
}
while(f!=null){
f=f.next;
s=s.next;
pre = pre.next;
}
pre.next = s.next;
return head;
}
}
SHEIN希音公司福利 363人发布
查看26道真题和解析