这道题目其实和输出链表的倒数第n个结点是基本上一致的。https://blog.nowcoder.net/n/4e57664df6974486bc352aa5a1e4613c
和上一道题一样,定义快慢指针,快指针先走n步,然后快慢指针一起走,快指针走到空的时候慢指针正好在倒数第n个结点上。
区别的地方只是在于要删除某个结点的话,我们需要知道它的前一个结点是什么。
如果要删除的结点是链表头结点的话(这个时候没有前一个结点)。这种情况下我们进行一下特判就可以了。
c++
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
ListNode* fast = head;
ListNode* slow = head;
ListNode* pre = head;
for(int i = 0 ; i < n ; i++)
{
fast = fast->next;
}
while(fast!=NULL)
{
fast = fast->next;
pre = slow;
slow = slow->next;
}
ListNode* target;
if(slow!=head)
{
target = pre->next;
pre->next = target->next;
}
else{
target = head;
head = head->next;
}
delete target;
return head;
}
};
java
import java.util.*;
public class Solution {
public ListNode removeNthFromEnd (ListNode head, int n) {
ListNode fast = head;
ListNode slow = head;
ListNode pre = head;
for(int i = 0 ; i < n ; i++){
fast = fast.next;
}
while(fast!=null){
fast = fast.next;
pre = slow;
slow = slow.next;
}
ListNode target;
if(slow!=head){
target = pre.next;
pre.next = target.next;
}
else{
target = head;
head = head.next;
}
return head;
}
}
python
class Solution:
def removeNthFromEnd(self , head , n ):
fast = head
slow = head
pre = head
for i in range(0,n):
fast = fast.next
while fast!=None:
fast = fast.next
pre = slow;
slow = slow.next
if slow!=head:
target = pre.next
pre.next = target.next
else:
target = head
head = head.next
return head

京公网安备 11010502036488号