文章目录
题目
给你一个链表,删除链表的倒数第 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]
提示:
- 链表中结点的数目为 sz
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
思路
算法:
双指针算法 O(n)
1、创建虚拟结点dummy
,dummy
指向head.next
2、指针first
,second
初始化均指向dummy
,first
指针走n
步,first
,second
指针同时向后走,直到first
走到末尾时终止
3、这样找到了删除结点的前一个结点,让前一个结点指向删除结点的后一个结点即可
时间复杂度:只遍历一次链表,所以总的时间复杂度为 O(n) .
代码
C++代码:
cpp
/**
* 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(-1);
dummy->next = head;
ListNode* first = dummy;
ListNode* second = dummy;
for(int i = 0; i <= n; i++) first = first->next;
while(first){
first = first->next;
second = second->next;
}
second->next = second->next->next;
return dummy->next;
}
};
python3代码:
py
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# Two pointer, One pass
dummy = ListNode(0)
dummy.next = head
fast = slow = dummy
for _ in range(n):
fast = fast.next
while fast and fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next