题目:
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
思路:
根据题目描述中的例子,如果要删除倒数第2个节点,那么需要拿到指向倒数第3个节点的指针pre。执行pre->next = pre->next->next,即可删除倒数第2个节点。
https://leetcode.cn/problems/remove-nth-node-from-end-of-list/solutions/2380859/lian-biao-quan-wang-zui-qing-xi-fu-shua-gsj8p/
C++:
struct ListNode
{
int val;
ListNode *next;
ListNode(int x)
{
val = x;
next = nullptr;
}
ListNode(int x, ListNode *next)
{
val = x;
next = next;
}
};
class Solution
{
public:
ListNode* removeNode(ListNode* head,int n)
{
// 初始化一个空结点,初始赋值为0,并且tempHead的下一个next指针指向head,指针指向为tempHead
ListNode* temphead = new ListNode(0,head);
ListNode* left = temphead;
ListNode* right = head;
//right先走n步
for(int i=0;i<n;i++)
{
right = right->next;
}
while(right != nullptr)
{
left = left->next;
right = right->next;
}
//删除倒数第n个节点
ListNode* temp = left->next;
left->next = left->next->next;
delete temp;
return temphead->next;
}
};
python:
思路:要找到倒数第n个,只要快指针比慢指针先走n步,这样快指针到结尾的时候慢指针就是我们想要到节点。
class ListNode:
def __init__(self,val=0,next=None):
self.val = val
self.next = next
class Solution:
def removeNode(self,head,n):
# 创建两个next指向头结点的指针
slow = dummy_head = ListNode(next=head)
fast = head
while fast and n:
fast = fast.next
n -= 1
while fast:
fast=fast.next
slow=slow.next
slow.next = slow.next.next
return dummy_head