19. 删除链表的倒数第N个节点
题目链接
链表倒数第N个节点是经典双指针题目,让两个指针保持n个间距,然后同步向后移动,当后面的指针会指向空时,此时前面的指针刚好在n位置。
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* ans = new ListNode();
ans->next = head;
ListNode* p = head;
ListNode* p1 = ans;
while(n--)
{
p = p->next;
}
while(p != nullptr)
{
p1 = p1->next;
p = p->next;
}
p1->next = p1->next->next;
return ans->next;
}
};
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:
ans = ListNode(0, head)
p = head
p1 = ans
for i in range(0, n):
p = p.next
while(p != None):
p = p.next
p1 = p1.next
p1.next = p1.next.next
return ans.next
如果对你有帮助的话,请点个赞哦!