题目描述
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
例子
# 例1
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
# 例2
输入:head = [1], n = 1
输出:[]
# 例3
输入:head = [1,2], n = 1
输出:[1]
解题思路
使用双指针法
首先定义一个虚拟头结点,
然后定义两个指针,fast
指针 和 slow
指针均指向虚拟头结点
然后,fast
指针先往前移 n + 1
然后,slow
指针和 fast
指针同时前移,直到 fast
指针为空,结束
然后此时 slow
指针 指向被删除元素的前一个,删除元素,然后返回实际头节点
代码
(C++)
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* dummyhead = new ListNode(0, head);
// 定义双指针
ListNode* fast = dummyhead;
ListNode* slow = dummyhead;
// fast指针右移 n+1
while ((n--) && (fast != NULL)) {
fast = fast->next;
}
fast = fast->next;
// fast 和 slow 同时右移
while (fast != NULL) {
fast = fast->next;
slow = slow->next;
}
// 删除元素
slow->next = slow->next->next;
head = dummyhead->next;
delete dummyhead;
return head;
}
};
(Python)
# 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:
# 定义虚拟头结点,双指针
dummyhead = ListNode(0, head)
slow = fast = dummyhead
# fast指针右移 n+1
while ((n>0) and (fast)):
n -= 1
fast = fast.next
fast = fast.next
# 将fast指针 和 slow指针 同时右移
while (fast):
slow = slow.next
fast = fast.next
# 删除元素
slow.next = slow.next.next
return dummyhead.next # 返回头结点