给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
--
快慢指针 1.0
注意对第二指针做判断,有可能链表长度还没有数字大
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode f=head,s=head;
while(f!=null && f.next!=null){
f=f.next;
if(n>0){
n--;
}else{
s=s.next;
}
}
if (n == 0) {
s.next = s.next.next;
} else {
if (n == 1) {
head=head.next;
return head;
}
}
return head;
}
}
--
快慢指针 2.0
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode left=head;
ListNode right=head;
if(n==1 && head.next==null){
return null;
}
while(right!=null){
right=right.next;
--n;
if(n<0 && right!=null){
left=left.next;
}
}
//这里是对删除第一个节点做判断
if(n==0){
head=head.next;
}else{
left.next=left.next.next;
}
return head;
}
}