leetcode刷题系列----模式2(Datastructure 链表)- 19:Remove Nth Node from End of List (Medium) 删除链表中的倒数第N个节点
Tips
- 更多题解请见本系列目录
- 使用双指针(快慢)解决。
- 此时定义一个新的链表,它头指针为0,指向的头结点为head,low指针在次链表上更新到下一节点。
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
fast = head
dummy = ListNode(0, head)
low = dummy
for i in range(n): fast=fast.next
while(fast):
fast=fast.next
low=low.next
low.next=low.next.next
return dummy.next
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0, head);
ListNode* fast = head;
ListNode* low = dummy;
for(int i=0;i<n;i++) fast=fast->next;
while(fast!=nullptr)
{
low = low->next;
fast = fast->next;
}
low->next=low->next->next;
return dummy->next;
}
};
C#
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode fast = head;
ListNode low = dummy;
for(int i=0;i<n;i++) fast=fast.next;
while(fast!=null)
{
low = low.next;
fast = fast.next;
}
low.next=low.next.next;
return dummy.next;
}
}
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode fast = head;
ListNode low = dummy;
for(int i=0;i<n;i++) fast=fast.next;
while(fast!=null)
{
low = low.next;
fast = fast.next;
}
low.next=low.next.next;
return dummy.next;
}
}